Guest User

Untitled

a guest
Jul 17th, 2018
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.99 KB | None | 0 0
  1.  
  2. # Requires Python 2.7 for latest itertools functions.
  3.  
  4. import itertools
  5.  
  6. allnums = [3,3,7,7]
  7. # [3, 3, 7, '/', '+', 7, '*'] # RPN
  8. # == 3 + (3/7) * 7
  9. # == 24
  10. allnums = [1,3,4,6]
  11. # [6, 1, 3, 4, '/', '-', '/']) # RPN
  12. # == 6 / (1 - (3/4))
  13. # == 24
  14.  
  15. target = 24
  16.  
  17. allops = {
  18. "+": (lambda a,b: a+b),
  19. "-": (lambda a,b: a-b),
  20. "*": (lambda a,b: a*b),
  21. # Convert to floating point (and use epilson for comparison below) to
  22. # allow (approximate) fractional calculation.
  23. "/": (lambda a,b: float(a)/b),
  24. }
  25.  
  26. def rpncalc(input):
  27. stack = []
  28. for i in input:
  29. if isinstance(i, str): # op
  30. try:
  31. b, a = stack.pop(), stack.pop()
  32. except IndexError:
  33. result = "illegal"
  34. break
  35. try:
  36. stack.append(allops[i](a, b))
  37. except ZeroDivisionError:
  38. result = "NaN"
  39. break
  40. else:
  41. stack.append(i)
  42. else:
  43. result = stack[-1]
  44. return result
  45.  
  46. def doit():
  47. numperms = set()
  48. for perm in itertools.permutations(allnums, 4):
  49. if perm in numperms:
  50. continue
  51. numperms.add(perm)
  52. results = set()
  53. for opnames in itertools.product(allops.keys(), repeat=3):
  54. for nums in numperms:
  55. # This permutations isn't quite right: creates dupes in the whole
  56. # set because we've already done the other orders.
  57. for ordering in itertools.permutations(nums[2:] + opnames[:-1]):
  58. input = list(nums[:2])
  59. input += ordering
  60. input.append(opnames[-1])
  61. result = rpncalc(input)
  62. if not isinstance(result, (int, float)):
  63. pass
  64. else:
  65. print "rpncalc(%s) = %s" % (input, result)
  66. results.add(result)
  67. if abs(target - result) < 0.1: # epsilon
  68. print "Found it!"
  69. return
  70. print sorted(results)
  71.  
  72. doit()
Add Comment
Please, Sign In to add comment