Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import random
- def constrained_sum_sample_pos(n, total):
- """Return a randomly chosen list of n positive integers summing to total.
- Each such list is equally likely to occur."""
- dividers = sorted(random.sample(xrange(1, total), n - 1))
- return [a - b for a, b in zip(dividers + [total], [0] + dividers)]
- success = False
- while True:
- solutions = 0
- correct = False
- while not correct:
- random_values = constrained_sum_sample_pos(4, 40)
- if len(list(set(random_values))) == 4:
- correct = True
- # if 1 in random_values:
- # correct = True
- print "Testing: ", random_values
- for weight in range (1, 41):
- success = False
- for y in range (0, 4):
- A = random_values[y]
- B = random_values[(y + 1) % 3]
- C = random_values[(y + 2) % 3]
- D = random_values[(y + 3) % 3]
- if A == weight:
- print "{0} == [{1}]".format(str(A), str(weight))
- success = True
- elif A + weight == B:
- print "{0} + [{1}] == {2}".format(str(A), str(weight), str(B))
- success = True
- elif A + weight == C:
- print "{0} + [{1}] == {2}".format(str(A), str(weight), str(B))
- success = True
- elif A + weight == D:
- print "{0} + [{1}] == {2}".format(str(A), str(weight), str(B))
- success = True
- elif A + B == weight:
- print "{0} + {1} == [{2}]".format(str(A), str(B), str(weight))
- success = True
- elif A + B + C == weight:
- print "{0} + {1} + {2} == [{3}]".format(str(A), str(B), str(C), str(weight))
- success = True
- elif A + B + weight == C:
- print "{0} + {1} + [{2}] == {3}".format(str(A), str(B), str(weight), str(C))
- success = True
- elif A + B == weight + C:
- print "{0} + {1} == [{2}] + {3}".format(str(A), str(B), str(weight), str(C))
- success = True
- elif A + B == weight + D:
- print "{0} + {1} == [{2}] + {3}".format(str(A), str(B), str(weight), str(D))
- success = True
- elif A + B + C == D + weight:
- print "{0} + {1} + {2} == {3} + [{4}]".format(str(A), str(B), str(C), str(D), str(weight))
- success = True
- elif A + B + C + weight == D:
- print "{0} + {1} + {2} + [{3}] == {4}".format(str(A), str(B), str(C), str(D), str(weight))
- success = True
- if success is True:
- solutions += 1
- break
- if success is False:
- break
- if solutions > 15:
- raw_input("")
- if success == True:
- print "Found: ", random_values
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement