问题描述:You have two jugs: a A-gallon jug and a B-gallon jug ( A > B ). Neither of the jugs have markings on them. There is a pump that can be used to fill the jugs with water. How can you get exactly C gallons of water in the A-gallon jug? Suppose the B <= C <= A and they are integer.
算法实现:
def jar(large_size, small_size, want, jar_large=0, jar_small=0, round=1):
"""
large_size: 大罐的容积
small_size: 小罐的容积
want: 希望最终取到的水的体积
jar_large: 此时大罐中的水的体积
jar_small: 此时小罐中的水的体积
round: 进行了多少轮取水
"""
print('round:%s' % round)
# 若大罐尺寸和小罐头线性相关,
# 除非want和他们俩也线性相关,
# 否则不可能完成
if large_size % small_size == 0 and \
large % want != 0 and \
small_size != 1:
return False
# 如果want是小罐容量的倍数,
# 且小于大罐容量,则进行want/small_size次就可以完成
if want % 3 == 0 and want < large_size:
return want, 0
# 基本情况(base case)
if jar_large == want:
return jar_large, jar_small
elif jar_small == want:
jar_large = jar_small
jar_small = 0
return jar_large, jar_small
# 正常递归程序(normal process)
# 如果大罐为空,将大罐灌满
elif jar_large == 0:
jar_display(large_size, jar_small)
return jar(large_size, small_size, want,
large_size, jar_small, round+1)
# 如果大罐中的水大于小罐的最大容量
# 用大罐将小罐灌满,然后将小罐倒空
elif jar_large > small_size:
jar_display(jar_large-small_size+jar_small, 0)
return jar(large_size, small_size, want,
jar_large-small_size+jar_small, 0, round+1)
# 否则,大罐中的水少于小罐容量,
# 将大罐中的水倒入小罐
else:
jar_display(0, jar_large)
return jar(large_size, small_size, want,
0, jar_large, round+1)
def jar_display(jar_large, jar_small):
print('------------------')
print('large:%s\nsmall:%s' % (jar_large, jar_small))
print('------------------')
程序测试代码:
def main():
large_size = 10
small_size = 3
for i in range(1, large_size+1):
jarLarge, jarSmall = jar(large_size, small_size, i)
print('finished:\nlarge:%s\nsmall:%s' % (jarLarge, jarSmall))
main()