简体   繁体   中英

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.

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

Build the new string from the previous one, slicing and rearranging.

string = "hello"
for pos in range(len(string)-1):
    # swap the chars at locations pos and pos+1
    string = string[:pos] + string[pos+1] + string[pos] + string[pos+2:]
    print(string)

Output:

ehllo
elhlo
ellho
elloh

That handles moving one character from the front to the back. Now, just repeat that once for each character in the string; it's a simple counting loop, with no reference to the actual characters. I trust that you can finish from here.

If you change your print line to include the original string you will see that it is not being modified by your function.

print(move_char_by_increment(string, char, i), string)

This outputs:

hello hello
ehllo hello
elhlo hello
ellho hello
elloh hello
hello hello
hlelo hello
hlleo hello
hlloe hello
etc...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM