Reordering character triplets in Python

97 Views Asked by At

I've been trying to solve this homework problem for days, but can't seem to fix it. I started my study halfway through the first semester, so I can't ask the teacher yet and I hope you guys can help me. It's not for grades, I just want to know how.

I need to write a program that reads a string and converts the triplets abc into bca. Per group of three you need to do this. For examplekatzonbecomesatkonz`.

The closest I've gotten is this:

string=(input("Give a string: "))

for i in range(0, len(string)-2):
    a = string[i]
    b = string[i + 1]
    c = string[i + 2]
    new_string= b, c, a
    i+=3
    print(new_string)

The output is:

('a', 't', 'k')
('t', 'z', 'a')
('z', 'o', 't')
('o', 'n', 'z')
1

There are 1 best solutions below

0
On

The code below converts for example "abc" to "bca". It works for any string containing triplets. Now, if input is "abcd", it is converted to "bcad". If you input "katzon", it is converted to "atkonz". This is what I understood from your question.

stringX = input()

# create list of words in the string
listX = stringX.split(" ")
listY = []

# create list of triplets and non-triplets
for word in listX:
    listY += [[word[i:i+3] for i in range(0, len(word), 3)]]

# convert triplets, for example: "abc" -> "bca"
for listZ in listY:
    for item in listZ:
        if len(item)==3:
            listZ[listZ.index(item)] = listZ[listZ.index(item)][1:] + listZ[listZ.index(item)][0]
    listY[listY.index(listZ)] = "".join(listZ)

# create final string
stringY = " ".join(listY)
print(stringY)