Advertisement
asweigart

Permutation Python

Jun 6th, 2021
205
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.78 KB | None | 0 0
  1. def getPerms(chars):
  2. print('Calling getPerms("' + chars + '")')
  3. if len(chars) == 1:
  4. # BASE CASE
  5. print('Base case, returning', chars)
  6. return [chars]
  7.  
  8. # RECURSIVE CASE
  9. permutations = []
  10. head = chars[0]
  11. tail = chars[1:]
  12. tailPermutations = getPerms(tail)
  13. for tailPerm in tailPermutations:
  14. print('For', chars, 'putting head', head, 'in all places in', tailPerm)
  15. for i in range(len(tailPerm) + 1):
  16. newPerm = tailPerm[0:i] + head + tailPerm[i:]
  17. print('New permutation:', newPerm)
  18. permutations.append(newPerm)
  19. print('All permutations of', chars, 'are', permutations)
  20. return permutations
  21.  
  22. print('Permutations of "ABC":')
  23. print('Result:', ','.join(getPerms('ABC')))
  24.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement