Advertisement
Guest User

Untitled

a guest
May 27th, 2015
265
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.77 KB | None | 0 0
  1. import random
  2. def constrained_sum_sample_pos(n, total):
  3. """Return a randomly chosen list of n positive integers summing to total.
  4. Each such list is equally likely to occur."""
  5.  
  6. dividers = sorted(random.sample(xrange(1, total), n - 1))
  7. return [a - b for a, b in zip(dividers + [total], [0] + dividers)]
  8.  
  9. success = False
  10. while True:
  11. solutions = 0
  12. correct = False
  13. while not correct:
  14. random_values = constrained_sum_sample_pos(4, 40)
  15. if len(list(set(random_values))) == 4:
  16. correct = True
  17. # if 1 in random_values:
  18. # correct = True
  19. print "Testing: ", random_values
  20.  
  21. for weight in range (1, 41):
  22. success = False
  23. for y in range (0, 4):
  24. A = random_values[y]
  25. B = random_values[(y + 1) % 3]
  26. C = random_values[(y + 2) % 3]
  27. D = random_values[(y + 3) % 3]
  28. if A == weight:
  29. print "{0} == [{1}]".format(str(A), str(weight))
  30. success = True
  31. elif A + weight == B:
  32. print "{0} + [{1}] == {2}".format(str(A), str(weight), str(B))
  33. success = True
  34. elif A + weight == C:
  35. print "{0} + [{1}] == {2}".format(str(A), str(weight), str(B))
  36. success = True
  37. elif A + weight == D:
  38. print "{0} + [{1}] == {2}".format(str(A), str(weight), str(B))
  39. success = True
  40. elif A + B == weight:
  41. print "{0} + {1} == [{2}]".format(str(A), str(B), str(weight))
  42. success = True
  43. elif A + B + C == weight:
  44. print "{0} + {1} + {2} == [{3}]".format(str(A), str(B), str(C), str(weight))
  45. success = True
  46. elif A + B + weight == C:
  47. print "{0} + {1} + [{2}] == {3}".format(str(A), str(B), str(weight), str(C))
  48. success = True
  49. elif A + B == weight + C:
  50. print "{0} + {1} == [{2}] + {3}".format(str(A), str(B), str(weight), str(C))
  51. success = True
  52. elif A + B == weight + D:
  53. print "{0} + {1} == [{2}] + {3}".format(str(A), str(B), str(weight), str(D))
  54. success = True
  55. elif A + B + C == D + weight:
  56. print "{0} + {1} + {2} == {3} + [{4}]".format(str(A), str(B), str(C), str(D), str(weight))
  57. success = True
  58. elif A + B + C + weight == D:
  59. print "{0} + {1} + {2} + [{3}] == {4}".format(str(A), str(B), str(C), str(D), str(weight))
  60. success = True
  61. if success is True:
  62. solutions += 1
  63. break
  64. if success is False:
  65. break
  66. if solutions > 15:
  67. raw_input("")
  68.  
  69. if success == True:
  70. print "Found: ", random_values
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement