Skip to content
Advertisement

Python – Move each character until end of string without reusing original string

I’m trying to move each character in a string, until the end of the string, and print each of those. But, without reusing the original string.

So say for the string “hello”, the result would be:

hello
ehllo
elhlo
ellho
elloh # here it use this string from the last result, instead of the original one
leloh
lleoh
...
hello # last result

In the above example, the original string appear two times, even though i said “without reusing original string” but bear in mind it’s just there to illustrate the example better.

Here the code i made so far:

import sys

def move_char_by_increment(string, char, increment):
        char_list = list(string)
        old_index = char_list.index(char)
        char = char_list.pop(old_index)
        new_index = old_index + increment
        char_list.insert(new_index, char)
        return ''.join(char_list)


string = sys.argv[1]
total_char_input = len(string)

for char in string:
        for i in range(0,total_char_input):
                print(move_char_by_increment(string, char, i))
sys.exit()

This succeed in moving character one by one until end of string, But, it does reuse the original string instead of doing it like in the above example…i couldn’t find a way to make it do what i want.

Advertisement

Answer

It is kind of like insertion sort. Do you like this answer?

lst = list("hello")
for _ in range(len(lst)):
    for i in range(len(lst) - 1):
        lst[i], lst[i + 1] = lst[i + 1], lst[i]
        print("".join(lst))

output

ehllo
elhlo
ellho
elloh
leloh
lleoh
lloeh
llohe
llohe
lolhe
lohle
lohel
olhel
ohlel
ohell
ohell
hoell
heoll
helol
hello
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement