0

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.

Dmitriy
  • 3,305
  • 7
  • 44
  • 55
  • It is a recursively calling permutations function on sliced string. string[1:] means slice of string[start:end]. Here is the nice reading material on slices https://developers.google.com/edu/python/strings#string-slices – MrKulli Nov 19 '19 at 01:10

1 Answers1

0

It's doing a recursion, a popular concept in programming. In every iteration, it calls the same function with a new string as argument which you obtain after slicing "string[1:]"

Hope this helps.

Deep
  • 616
  • 1
  • 9
  • 17