Last active
July 28, 2017 22:11
-
-
Save cameronp98/973b2db6915a2ec2c349 to your computer and use it in GitHub Desktop.
http://www.problemotd.com/problem/balancing-act/ -- find the smallest of 9 items only accessing the 'scales' twice
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| """ | |
| http://www.problemotd.com/problem/balancing-act/ | |
| ------------------------------------------------------------------------------ | |
| Problem: You are given 9 balls and a balance scale. One of the balls weighs | |
| slightly less than the other 8. Using the scale only twice how can you figure | |
| out which ball weighs less than the others? Do not attempt to mark the ball | |
| once you find it. | |
| ------------------------------------------------------------------------------ | |
| find the smallest of 9 items only accessing the 'scales' twice | |
| ------------------------------------------------------------------------------ | |
| Cameron Phillips - 19/03/2014 - Python 3.3.3 | |
| """ | |
| # equivalent to using weighing scales | |
| def lightest_of_pair(a, b): | |
| print("USED SCALES") | |
| if isinstance(a, list): | |
| va, vb = sum(i[1] for i in a), sum(i[1] for i in b) | |
| else: | |
| va, vb = a[1], b[1] | |
| if va == vb: | |
| return None | |
| if va < vb: | |
| return a | |
| return b | |
| def lightest_of_group(group): | |
| lightest = lightest_of_pair(group[0],group[1]) | |
| if lightest == None: | |
| return group[2] | |
| return lightest | |
| def balancing_act(balls): | |
| # split into 3 groups of 3 | |
| (a, b, c) = (balls[i:i+3] for i in range(0,8,3)) | |
| lightest = lightest_of_pair(a, b) | |
| if lightest == None: | |
| return lightest_of_group(c) | |
| return lightest_of_group(lightest) | |
| # balls 'A' to 'H' have weight 5, ball 'X', the target, has weight 4 | |
| balls = [(chr(65+i), 5) for i in range(8)] + [('X', 4)] | |
| print(balancing_act(balls)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment