Advertisement
Guest User

Untitled

a guest
May 21st, 2015
543
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.82 KB | None | 0 0
  1. import fractions
  2. import itertools
  3.  
  4. def calculate_result(numbers, respect_order_of_operations, allow_non_integer_division):
  5. def divides(x,y):
  6. return x % y == 0
  7. a,b,c,d,e,f,g,h,i = numbers
  8. if respect_order_of_operations:
  9. #a + (13*b/c) + d + (12*e) - f - 11 + (g*h/i) - 10 = 66
  10. if not allow_non_integer_division:
  11. if not divides(13*b, c): return None
  12. if not divides(g * h, i): return None
  13. return a + (13*b//c) + d + (12*e) - f - 11 + (g*h//i) - 10
  14. else:
  15. #(((((((((((a+13)*b)/c)+d)+12)*e)-f)-11)+g)*h)/i)-10 = 66
  16. if not allow_non_integer_division:
  17. if not divides((a+13)*b, c): return None
  18. if not divides((((((((((a+13)*b)/c)+d)+12)*e)-f)-11)+g)*h, i): return None
  19. return (((((((((((a+13)*b)/c)+d)+12)*e)-f)-11)+g)*h)/i)-10
  20.  
  21. def get_all_solutions(respect_order_of_operations, allow_non_integer_division, allow_duplicate_numbers):
  22. digits = map(fractions.Fraction, range(1,10))
  23. possibilities = itertools.product(digits, repeat=len(digits)) if allow_duplicate_numbers else itertools.permutations(digits)
  24. for numbers in possibilities:
  25. if calculate_result(numbers, respect_order_of_operations, allow_non_integer_division) == 66:
  26. yield map(int, numbers)
  27.  
  28. for respect_order_of_operations in [True, False]:
  29. for allow_non_integer_division in [False]:
  30. for allow_duplicate_numbers in [False]:
  31. print "Respecting order of operations:", respect_order_of_operations
  32. print "Allowing non-integer division:", allow_non_integer_division
  33. print "Allowing duplicate numbers:", allow_duplicate_numbers
  34. for solution in get_all_solutions(respect_order_of_operations, allow_non_integer_division, allow_duplicate_numbers):
  35. print solution
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement