fork download
  1. # Fun with linked lists.
  2.  
  3. from functools import reduce
  4.  
  5. class Node:
  6. def __init__(self, val=None, next=None):
  7. self.val = val
  8. self.next = next
  9.  
  10. def __str__(self):
  11. return '#(' + ' '.join(map(str, ltoa(self))) + ')'
  12.  
  13. def atol(a):
  14. # Array to linked-list.
  15. return reduce(lambda init, x: Node(x, init), reversed(a), None)
  16.  
  17. def ltoa(l):
  18. # Linked-list to array.
  19. return reducelp(lambda init, x: init + [x.val], l, [])
  20.  
  21. def reducelp(f, l, init):
  22. while l:
  23. init = f(init, l)
  24. l = l.next
  25. return init
  26.  
  27. def _append(tail, l):
  28. while l:
  29. tail.next = Node(l.val)
  30. tail = tail.next
  31. l = l.next
  32. return tail
  33.  
  34. def appendl(ls):
  35. temp = Node()
  36. reducelp(lambda init, x: _append(init, x.val), ls, temp)
  37. return temp.next
  38.  
  39. def reversel(l):
  40. return reducelp(lambda init, x: Node(x.val, init), l, None)
  41.  
  42. def mapl(f, l):
  43. return maplp(lambda x: f(x.val), l)
  44.  
  45. def maplp(f, l):
  46. return reversel(reducelp(lambda init, x: Node(f(x), init), l, None))
  47.  
  48. def appendmaplp(f, l):
  49. return appendl(maplp(f, l))
  50.  
  51. def combinationsl(l, k):
  52. if k == 0:
  53. return Node()
  54. return appendmaplp(lambda r: mapl(lambda c: Node(r.val, c),
  55. combinationsl(r.next, k-1)), l)
  56.  
  57. # Show.
  58.  
  59. n = 5
  60. l1 = atol(list(range(n)))
  61. l2 = atol(list(range(n, n*2)))
  62. l3 = atol(list(range(n*2, n*3)))
  63.  
  64. print(l1)
  65. print(ltoa(l1))
  66. print(reversel(l1))
  67. print(mapl(lambda x: x**2, l1))
  68. print(appendl(atol([None, l1, None, None, l2, None, None, l3, None])))
  69. print(appendmaplp(lambda x: Node(x.val), l1))
  70.  
  71. for k in range(n+1):
  72. print(f'{n} choose {k}')
  73. for x in ltoa(combinationsl(l1, k)):
  74. print(x)
Success #stdin #stdout 0.08s 14136KB
stdin
Standard input is empty
stdout
#(0 1 2 3 4)
[0, 1, 2, 3, 4]
#(4 3 2 1 0)
#(0 1 4 9 16)
#(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14)
#(0 1 2 3 4)
5 choose 0
None
5 choose 1
#(0)
#(1)
#(2)
#(3)
#(4)
5 choose 2
#(0 1)
#(0 2)
#(0 3)
#(0 4)
#(1 2)
#(1 3)
#(1 4)
#(2 3)
#(2 4)
#(3 4)
5 choose 3
#(0 1 2)
#(0 1 3)
#(0 1 4)
#(0 2 3)
#(0 2 4)
#(0 3 4)
#(1 2 3)
#(1 2 4)
#(1 3 4)
#(2 3 4)
5 choose 4
#(0 1 2 3)
#(0 1 2 4)
#(0 1 3 4)
#(0 2 3 4)
#(1 2 3 4)
5 choose 5
#(0 1 2 3 4)