Advertisement
Guest User

Untitled

a guest
Oct 18th, 2019
152
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.79 KB | None | 0 0
  1. # permutation与combination
  2.  
  3. 没事随手瞎写的,性能明显不是最好的,而且也没有完全使用生成器
  4.  
  5. ```py
  6. # coding=utf-8
  7.  
  8. import itertools
  9.  
  10.  
  11. def combinations(l, n):
  12. if len(l) < n:
  13. raise StopIteration
  14. if n == 0:
  15. yield ()
  16. else:
  17. a0 = l[0]
  18. ax = l[1:]
  19. for r in combinations(ax, n - 1):
  20. yield (a0, ) + r
  21. for r in combinations(ax, n):
  22. yield r
  23.  
  24.  
  25. def permutations(l, n):
  26. if len(l) < n:
  27. raise StopIteration
  28. if n == 0:
  29. yield ()
  30. else:
  31. for i, x in enumerate(l):
  32. ax = l[:i] + l[i + 1:]
  33. for r in permutations(ax, n - 1):
  34. yield (x, ) + r
  35.  
  36.  
  37. for p in combinations([1, 2, 3], 1):
  38. print(p)
  39.  
  40. for p in permutations([1, 2, 3], 3):
  41. print(p)
  42. ```
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement