题目是这样的:
12个球,其中一个质量和其余的不同,用一个无砝码的天平最多分3次称出。以前考虑过,但最终得出了一个错误的结论。这次应 quanben 之请再想了一下,大致如下解法:
# vim: set sts=4 ts=4 sw=4 et:
# twlvball.py: solves the twelve balls problem.
import sys
import operator
class Ball():
def __init__(self, num, w):
self.num = num
self.weight = w
def main():
print "This program is fragile. Try not to enter wrong arguments."
sys.stdout.write("ball number[0-11]: ")
num = int(sys.stdin.readline().rstrip())
assert 0 <= num and num < 12
sys.stdout.write("weight[h/l]: ")
w = sys.stdin.readline().rstrip()
assert w in ["h", "l"]
test(num, w)
def test(num, w):
balls = []
for i in range(12):
balls.append(Ball(i, 100))
balls[num].weight = (150 if w == "h" else 50)
print solve(balls)
def solve(balls):
# weigh 4 left, 4 right and 4 free.
res0 = weigh(balls[0:4], balls[4:8])
if res0 == 0:
# in 4 free: 8, 9, 10, 11; weigh 1 left, 1 right and 2 free.
if weigh(balls[8:9], balls[9:10]) != 0:
# in 2 weighed; weigh 1 good left and 1 unsure right.
12个球,其中一个质量和其余的不同,用一个无砝码的天平最多分3次称出。以前考虑过,但最终得出了一个错误的结论。这次应 quanben 之请再想了一下,大致如下解法:
# vim: set sts=4 ts=4 sw=4 et:
# twlvball.py: solves the twelve balls problem.
import sys
import operator
class Ball():
def __init__(self, num, w):
self.num = num
self.weight = w
def main():
print "This program is fragile. Try not to enter wrong arguments."
sys.stdout.write("ball number[0-11]: ")
num = int(sys.stdin.readline().rstrip())
assert 0 <= num and num < 12
sys.stdout.write("weight[h/l]: ")
w = sys.stdin.readline().rstrip()
assert w in ["h", "l"]
test(num, w)
def test(num, w):
balls = []
for i in range(12):
balls.append(Ball(i, 100))
balls[num].weight = (150 if w == "h" else 50)
print solve(balls)
def solve(balls):
# weigh 4 left, 4 right and 4 free.
res0 = weigh(balls[0:4], balls[4:8])
if res0 == 0:
# in 4 free: 8, 9, 10, 11; weigh 1 left, 1 right and 2 free.
if weigh(balls[8:9], balls[9:10]) != 0:
# in 2 weighed; weigh 1 good left and 1 unsure right.