Here is the code that actually works. It returns all possible permutations of a given string of any length
eg: Permutations('ab') returns ['ab','ba]
def permutations(string):
if len(string) == 1: return set(string)
first = string[0]
rest = permutations(string[1:]) #This is the line that i do not understand
result = set()
for i in range(0, len(string)):
for p in rest:
result.add(p[0:i] + first + p[i:])
return result
I do not know what the line(commented above) rest = permutations(string[1:])
is doing.
I tried writing it like this rest = string[1:]
, however it doesn't work properly when written like this.
What is the difference between these two lines of code?
rest = permutations(string[1:])
and
rest = string[1:]
it seems to be calling itself inside the function but i am unsure as to how that would make a difference.