I am new at python and very bad at thinking in a recursive way. This code gives me an IndexError: string index out of range
. And I have no idea how to correct it.
def get_permutations(sequence):
def permutationhelp(sequence,chosen):
if sequence=="":
print(chosen)
else:
for i in range(len(sequence)):
c= sequence[i]
chosen +=c
sequence=sequence[i+1:]
permutationhelp(sequence,chosen)
sequence=c+sequence
chosen=chosen[:-1]
def permutation(sequence):
permutationhelp(sequence,"")
return permutation(sequence)
Example:
get_permutations('abc')
['abc', 'acb', 'bac', 'bca', 'cab', 'cba']
The Traceback is this:
Traceback (most recent call last):
File "soRecursivePermutations.py", line 25, in <module>
get_permutations('abc')
File "soRecursivePermutations.py", line 23, in get_permutations
return permutation(sequence)
File "soRecursivePermutations.py", line 20, in permutation
permutationhelp(sequence,"")
File "soRecursivePermutations.py", line 12, in permutationhelp
c= sequence[i]
IndexError: string index out of range
The reason for your Traceback is here:
sequence=sequence[i+1:]
permutationhelp(sequence,chosen)
sequence=c+sequence
The first line leaves sequence
with just the end of the string. and the third line only adds one character back onto sequence
, so sequence
gets shorter as you go through the loop.
However, this is probably the program you were looking for:
# https://stackoverflow.com/a/53088155/4834
def remove_at(i, s):
return s[:i] + s[i + 1:]
def permutationhelp(sequence, chosen, collect):
if sequence == "":
collect.append(chosen)
else:
for i,c in enumerate(sequence):
permutationhelp(remove_at(i, sequence), chosen + c, collect)
def get_permutations(sequence):
collect = []
permutationhelp(sequence, "", collect)
return collect
print(get_permutations('abc'))
Output:
['abc', 'acb', 'bac', 'bca', 'cab', 'cba']