我正在学习一门离散的数学课程,这需要我为它写一些简短的代码。这就是我要面对的问题:
开发一个Python方法change( amount ),对于24到1000范围内的任何整数,返回一个仅由数字5和7组成的列表,使它们的和等于amount。例如,change(28)可以返回7,7,7,7,而change(49)可以返回7,7,7,7,7,7,7或5,5,5,5,5,5,5,5,7,7或7,5,5,5,5,5,5,7。
(要解决此测验,请在您的计算机上实现方法更改(数量),在多个输入上进行测试,然后将代码粘贴到下面的字段中并按下提交测验按钮。)
下面是我写的代码:
def change(amount):
if amount < 24:
return 0
assert(amount >= 24)
if amount == 24:
return [5, 5, 7, 7]
if amount == 25:
return [5, 5, 5, 5, 5]
if amount == 26:
return [5, 7, 7, 7]
if amount > 1000:
return 0
coins = change(amount - 5)
coins.append(5)
return coins
当我在代码可视化程序(http://www.pythontutor.com/visualize.html#mode=edit)上测试我的代码时,它似乎工作得很好,但当我输入它作为测验的答案时,我得到了一个错误:
RuntimeErrorElement(RuntimeError,第16行错误: coins.append(5) AttributeError:'int‘对象没有'append’属性)
我不知道发生了什么。请注意,这个类是一个在线类,我正在将代码输入到一个在线平台中,所以我确信算法正在检查某些东西,但我不确定是什么。
发布于 2018-07-22 07:47:05
确保所有返回值都是同一类型的。你需要使用数组,但是当你返回0的时候,你使用的是整型。已修复:
def change(amount):
if amount < 24:
return [0]
assert(amount >= 24)
if amount == 24:
return [5, 5, 7, 7]
if amount == 25:
return [5, 5, 5, 5, 5]
if amount == 26:
return [5, 7, 7, 7]
if amount > 1000:
return [0]
coins = change(amount - 5)
coins.append(5)
return coins
发布于 2018-07-22 17:25:11
谢谢大家!在阅读了您的评论并重新检查了我的错误后,我发现了我逻辑上的错误。如果没有你的帮助,我就不能相应地调整我的想法,我已经重写了下面的代码。我知道这不是最优雅的答案,但我想给出一个在我的Python知识范围内的答案,而不是简单地抄袭别人的工作。话虽如此,看到每个人都是如何解决这个问题的,这让我从另一个角度来看待它。
总而言之,我在逻辑上的错误是忘记了有一种情况,在这种情况下只有7,加或减一个5“硬币”不会解决它。
代码:
def change(amount):
assert(amount >= 24)
if amount == 24:
return [5, 5, 7, 7]
if amount == 25:
return [5, 5, 5, 5, 5]
if amount == 26:
return [5, 7, 7, 7]
if amount == 27:
return [5, 5, 5, 5 , 7 ]
if amount == 28:
return [ 7, 7, 7, 7]
if amount > 1000:
return 0
coins = change(amount - 5)
coins.append(5)
return coins
发布于 2019-02-23 14:51:48
def change(amount):
if amount < 24:
return [0]
assert(amount >= 24)
if amount == 24:
return [5, 5, 7, 7]
if amount == 25:
return [5, 5, 5, 5, 5]
if amount == 26:
return [5, 7, 7, 7]
if amount==27:
return [5,5,5,5,7]
if amount==28 :
return [7, 7, 7 ,7]
if amount > 1000:
return [0]
coins = change(amount - 5)
coins.append(5)
return coins
enter code here
change(987)
https://stackoverflow.com/questions/51460879
复制相似问题