Advertisement
Guest User

Untitled

a guest
Aug 23rd, 2016
59
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.51 KB | None | 0 0
  1. # This Python 3 script solves the "Four Fours" problem and similar problems.
  2.  
  3. # The example at the end of the script generates all combinations of [2,3,5,7]
  4. # that equal 10, using the operations of addition, subtraction, multiplication,
  5. # and division.
  6.  
  7. # Exact arithmetic is used. Only integer exponents between -99 and 99 are allowed.
  8.  
  9. from fractions import Fraction
  10.  
  11. def partitions(lst):
  12. def part(lst):
  13. if len(lst) == 1:
  14. yield (lst, [])
  15. else:
  16. first = lst[:-1]
  17. last = lst[-1:]
  18. for A, B in part(first):
  19. yield (A + last, B)
  20. yield (A, B + last)
  21.  
  22. for A, B in part(lst):
  23. if len(A) > 0 and len(B) > 0:
  24. yield A, B
  25.  
  26.  
  27. def generate(lst):
  28. if len(lst) == 1:
  29. x = lst[0]
  30. yield Fraction(x), str(x)
  31. else:
  32. for A, B in partitions(lst):
  33. for x, sx in generate(A):
  34. for y, sy in generate(B):
  35. yield x+y, "(%s + %s)" % (sx, sy)
  36. yield x-y, "(%s - %s)" % (sx, sy)
  37. yield y-x, "(%s - %s)" % (sy, sx)
  38. yield x*y, "(%s * %s)" % (sx, sy)
  39. if y != 0:
  40. yield x/y, "(%s / %s)" % (sx, sy)
  41. if x != 0:
  42. yield y/x, "(%s / %s)" % (sy, sx)
  43. if abs(y) < 100 and y == int(y) and (x != 0 or y > 0):
  44. yield x**y, "(%s ^ %s)" % (sx, sy)
  45. if abs(x) < 100 and x == int(x) and (y != 0 or x > 0):
  46. yield y**x, "(%s ^ %s)" % (sy, sx)
  47.  
  48.  
  49. if __name__ == "__main__":
  50. for n, s in generate([2,3,5,7]):
  51. if n == 10:
  52. print ("%s = %s" % (n, s))
  53.  
  54. """ Expected output:
  55.  
  56. 10 = (((2 ^ 3) - 5) + 7)
  57. 10 = (7 - (5 - (2 ^ 3)))
  58. 10 = ((2 + (3 * 5)) - 7)
  59. 10 = ((7 - (2 + 3)) * 5)
  60. 10 = (((2 ^ 3) + 7) - 5)
  61. 10 = (((3 ^ 2) - 7) * 5)
  62. 10 = (((7 - 2) - 3) * 5)
  63. 10 = (((7 - 2) * 3) - 5)
  64. 10 = (5 / ((7 / 2) - 3))
  65. 10 = (((3 + 7) / 2) + 5)
  66. 10 = (((7 - 3) - 2) * 5)
  67. 10 = (5 / (2 / (7 - 3)))
  68. 10 = (((7 - 3) / 2) * 5)
  69. 10 = ((2 + 3) * (7 - 5))
  70. 10 = ((2 ^ 3) - (5 - 7))
  71. 10 = ((2 ^ 3) + (7 - 5))
  72. 10 = ((7 - 3) / (2 / 5))
  73. 10 = ((5 / 2) * (7 - 3))
  74. 10 = ((2 - 7) * (3 - 5))
  75. 10 = ((2 - 7) + (3 * 5))
  76. 10 = ((7 - 2) * (5 - 3))
  77. 10 = ((3 * 5) - (7 - 2))
  78. 10 = (2 * ((3 - 5) + 7))
  79. 10 = (2 * (7 - (5 - 3)))
  80. 10 = (2 + ((3 * 5) - 7))
  81. 10 = (2 - (7 - (3 * 5)))
  82. 10 = (2 * ((3 + 7) - 5))
  83. 10 = (((7 - 3) * 5) / 2)
  84. 10 = (2 * (3 - (5 - 7)))
  85. 10 = (2 - ((5 - 7) ^ 3))
  86. 10 = (2 * (3 + (7 - 5)))
  87. 10 = (2 + ((7 - 5) ^ 3))
  88. """
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement