Advertisement
asweigart

recursive combination without repetition

Jun 7th, 2021
683
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.42 KB | None | 0 0
  1. def getCombos(chars, k):
  2. print("Start of getCombos('" + chars + "', " + str(k) + ")")
  3. if k == 0:
  4. # BASE CASE
  5. print("For getCombos('" + chars + "', " + str(k) + ") base case returns ['']")
  6. return [''] # If k asks for 0-combinations, return '' as the selection of zero letters from chars.
  7. elif chars == '':
  8. # BASE CASE - TODO - why does this *have* to come second?
  9. print("For getCombos('" + chars + "', " + str(k) + ') base case returns []')
  10. return [] # An empty set has no combinations for any k.
  11.  
  12. # RECURSIVE CASE
  13. combinations = []
  14. head = chars[:1]
  15. tail = chars[1:]
  16. print("For getCombos('" + chars + "', " + str(k) + ") part 1, get combos of tail '" + tail + "'")
  17. tailCombos = getCombos(tail, k - 1)
  18. print("For getCombos('" + chars + "', " + str(k) + ') part 1, combos of tail are', tailCombos)
  19. print(' Adding head', head, 'to tail combos:')
  20. for combo in tailCombos:
  21. print(' New combination', head + combo)
  22. combinations.append(head + combo)
  23.  
  24. print("For getCombos('" + chars + "', " + str(k) + ") part 2, include combos from getCombos('" + tail + "', " + str(k) + ')')
  25. combinations.extend(getCombos(tail, k))
  26.  
  27. print("For getCombos('" + chars + "', " + str(k) + ') results are', combinations)
  28. return combinations
  29.  
  30. #print('3-Combinations of "ABCD":')
  31. print('Results:', getCombos('ABC', 2))
  32.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement