使用循环和列表推导式两种方法求解百钱买百鸡问题。假设大鸡5 元一只,中鸡3 元一只,小鸡1 元三只,现有100 元钱想买100 只鸡,有多少种买法?
参考答案:【答案】(1 )循环
>>> for x in
range(21): for y
in range(34):
z = 100-x-y
if z%3==0 and 5*x + 3*y + z//3
== 100: print(x,y,z)
0 25 75
4 18 78
8 11 81
12 4 84
(2 )列表推导式
>>> [(x, y, 100-x-y) for x in range(21) for y in range(34) if (100-x-y)%3==0 and
5*x+3*y+(100-x-y)//3==100]
[(0, 25, 75), (4, 18, 78), (8, 11, 81), (12, 4, 84)]
【解析】
>>> for x in
range(21): for y
in range(34):
z = 100-x-y
if z%3==0 and 5*x + 3*y + z//3
== 100: print(x,y,z)
0 25 75
4 18 78
8 11 81
12 4 84
(2 )列表推导式
>>> [(x, y, 100-x-y) for x in range(21) for y in range(34) if (100-x-y)%3==0 and
5*x+3*y+(100-x-y)//3==100]
[(0, 25, 75), (4, 18, 78), (8, 11, 81), (12, 4, 84)]
【解析】
继续答题:下一题