Home > database >  How to encode (replace) parts of word from end to beginning for some N value (like abcabcab to cbacb
How to encode (replace) parts of word from end to beginning for some N value (like abcabcab to cbacb

Time:10-15

I would like to create a program for encoding and decoding words. Specifically, the program should take part of the word (count characters depending on the value of n) and turns them backwards. This cycle will be running until it encodes the whole word.
At first I created the number of groups of parts of the word which is the number of elements n some possible remainder *(For example for Language with n = 3 has 3 parts - two parts of 3 chars and one remainder with 2 chars).This unit is called a general.
Then, depending on the general, I do a cycle that n * takes the given character and always adds it to the group (group has n chars).

At the end of the group cycle, I add (in reverse order) to new_word and reset the group value.
The goal should be to example decode word Language with (n value = 2) to aLgnaueg.
Or Language with (n value = 3) to naL aug eg and so on.
Next example is word abcabcab (n=3) to cba cba ba ?

Output of my code don´t do it right. Output for n=3 is "naLaugeg"

Could I ask how to improve it? Is there some more simple python function how to rewrite it?

My code is there:

n = 3
word = "Language"


new_word = ""

group = ""

divisions =  (len(word)//n)
residue =  (len(word)%n)
general = divisions   residue

for i in range(general):
    j=2
    
    for l in range(n):
        group  = word[i j]
        print(word[i j], l)
        j=j-1
    
    
    for j in range((len(group)-1),-1,-1):
        new_word  = group[j]
        print(word[j])
        
    group = ""
    
    
print(group)    

print(new_word)

CodePudding user response:

import textwrap

n = 3
word = "Language"


chunks = textwrap.wrap(word, n)
reversed_chunks = [chunk[::-1] for chunk in chunks]

>>> print(' '.join(reversed_chunks))
naL aug eg
  • Related