Advertisement
asweigart

Untitled

Jun 5th, 2021
210
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.15 KB | None | 0 0
  1. def getCombosWithRepetition(chars, k, startFrom=None, prefix=None, results=None):
  2. if startFrom is None:
  3. startFrom = chars[0]
  4. if prefix is None:
  5. prefix = []
  6. if results is None:
  7. results = []
  8.  
  9. if len(prefix) == k:
  10. # BASE CASE
  11. results.append(''.join(prefix))
  12. return
  13.  
  14. # RECURSIVE CASE
  15. for char in chars[chars.find(startFrom):]:
  16. prefix.append(char)
  17. getCombosWithRepetition(chars, k, char, prefix, results)
  18. prefix.pop()
  19. return results
  20.  
  21. print(getCombosWithRepetition('ABCD', 4))
  22.  
  23.  
  24.  
  25. def getCombosWithRep2(chars, k):
  26. combos = []
  27. prefix = [chars[0]] * k
  28.  
  29. # Replace top of prefix with the next letter, of if it's the last letter, pop it.
  30. while True:
  31. combos.append(''.join(prefix))
  32.  
  33. while ''.join(prefix[-1]) == chars[-1]:
  34. prefix.pop()
  35. if prefix == []:
  36. return combos
  37.  
  38. nextCharIndex = chars.find(prefix[-1]) + 1
  39. prefix[-1] = chars[nextCharIndex]
  40.  
  41. while len(prefix) < k:
  42. prefix.append(prefix[-1])
  43.  
  44.  
  45.  
  46. print(getCombosWithRep2('ABCD', 4))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement