fork download
  1. def next_permutation(arr):
  2. #https://w...content-available-to-author-only...i.io/page/next-lexicographical-permutation-algorithm
  3. i = len(arr) - 1
  4. while i > 0 and arr[i - 1] >= arr[i]:
  5. i -= 1
  6. if i <= 0:
  7. return False
  8.  
  9. j = len(arr) - 1
  10. while arr[j] <= arr[i - 1]:
  11. j -= 1
  12. arr[i - 1], arr[j] = arr[j], arr[i - 1]
  13.  
  14. arr[i : ] = arr[len(arr) - 1 : i - 1 : -1]
  15. return True
  16.  
  17. def partitions(Sum, K, lst, Minn = 0):
  18. if K == 0:
  19. if Sum == 0:
  20. print("src partition: ", lst) # [3, 1, 0] denotes three zeros and one 1
  21. arr = []
  22. for i in range(len(lst)):
  23. if lst[i]:
  24. arr.extend([i]*lst[i])
  25. print(arr)
  26. while next_permutation(arr):
  27. print(arr)
  28. return
  29. for i in range(Minn, min(Sum + 1, Sum + 1)):
  30. partitions(Sum - i, K - 1, [i] + lst, i)
  31.  
  32. b = 4
  33. n = 5
  34. partitions(n, b, [])
Success #stdin #stdout 0.02s 9004KB
stdin
Standard input is empty
stdout
src partition:  [5, 0, 0, 0]
[0, 0, 0, 0, 0]
src partition:  [4, 1, 0, 0]
[0, 0, 0, 0, 1]
[0, 0, 0, 1, 0]
[0, 0, 1, 0, 0]
[0, 1, 0, 0, 0]
[1, 0, 0, 0, 0]
src partition:  [3, 2, 0, 0]
[0, 0, 0, 1, 1]
[0, 0, 1, 0, 1]
[0, 0, 1, 1, 0]
[0, 1, 0, 0, 1]
[0, 1, 0, 1, 0]
[0, 1, 1, 0, 0]
[1, 0, 0, 0, 1]
[1, 0, 0, 1, 0]
[1, 0, 1, 0, 0]
[1, 1, 0, 0, 0]
src partition:  [3, 1, 1, 0]
[0, 0, 0, 1, 2]
[0, 0, 0, 2, 1]
[0, 0, 1, 0, 2]
[0, 0, 1, 2, 0]
[0, 0, 2, 0, 1]
[0, 0, 2, 1, 0]
[0, 1, 0, 0, 2]
[0, 1, 0, 2, 0]
[0, 1, 2, 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