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:
JavaScript
x
10
10
1
hello
2
ehllo
3
elhlo
4
ellho
5
elloh # here it use this string from the last result, instead of the original one
6
leloh
7
lleoh
8
9
hello # last result
10
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:
JavaScript
1
19
19
1
import sys
2
3
def move_char_by_increment(string, char, increment):
4
char_list = list(string)
5
old_index = char_list.index(char)
6
char = char_list.pop(old_index)
7
new_index = old_index + increment
8
char_list.insert(new_index, char)
9
return ''.join(char_list)
10
11
12
string = sys.argv[1]
13
total_char_input = len(string)
14
15
for char in string:
16
for i in range(0,total_char_input):
17
print(move_char_by_increment(string, char, i))
18
sys.exit()
19
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?
JavaScript
1
6
1
lst = list("hello")
2
for _ in range(len(lst)):
3
for i in range(len(lst) - 1):
4
lst[i], lst[i + 1] = lst[i + 1], lst[i]
5
print("".join(lst))
6
output
JavaScript
1
21
21
1
ehllo
2
elhlo
3
ellho
4
elloh
5
leloh
6
lleoh
7
lloeh
8
llohe
9
llohe
10
lolhe
11
lohle
12
lohel
13
olhel
14
ohlel
15
ohell
16
ohell
17
hoell
18
heoll
19
helol
20
hello
21