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