项目:使用输入nickels
,pennies
,sum
创建一个Python代码,如果可以创建sum
的{{1}},则返回nickels
}和pennies
。
我的代码是:
def corect_change(nickles, pennies, summ):
result = False
i = 0
j = 0
while i <= nickles:
if summ == i * 5:
result = True
else:
while j <= pennies:
if summ == (i * 5) + j:
result = True
j += 1
i += 1
return result
print corect_change(5,3,11)
现在这适用于可以被5整除的总和但是当它必须包含便士时会失败。
有人可以告诉我为什么,并给我一些改进它的想法。
答案 0 :(得分:2)
您的代码存在一些问题:
i
从1 这里有几个实现基于首先使用尽可能多的镍,然后是便士。
def correct_change2(nickels, pennies, sum):
# While you have nickels left and sum is still more than 5 cents...
while sum > 5 and nickels:
sum -= 5
nickels -= 1
# You've removed as many nickels as you had or sum is now less than 5
# If you have enough pennies left, return True
return pennies >= sum
def correct_change(nickels, pennies, sum):
# Remove as many nickels as you have or as many as sum needs,
# whichever is less
sum -= 5 * min(nickels, sum / 5)
# You're out of nickels or sum is less than 5
# If you have enough pennies to equal sum, return True
return pennies >= sum
print correct_change(5,3,11)
此外,您的方法轻轻地重新安排工作:
def corect_change(nickles, pennies, summ):
i = 0
while i <= nickles:
if summ - (i * 5) < 5:
break
i += 1
j = 0
while j <= pennies:
if summ == (i * 5) + j:
break
j += 1
return summ == (i * 5) + j
但我们可以通过使用for循环和xrange()
:
def corect_change(nickles, pennies, summ):
for i in xrange(nickles):
if summ - (i * 5) < 5:
break
for j in xrange(pennies):
if summ == (i * 5) + j:
break
return summ == (i * 5) + j