首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >为什么我在硬币更改程序(Python3)中得到“AttributeError:'int‘对象没有属性'append’)”?

为什么我在硬币更改程序(Python3)中得到“AttributeError:'int‘对象没有属性'append’)”?
EN

Stack Overflow用户
提问于 2018-07-22 07:31:38
回答 3查看 6.8K关注 0票数 1

我正在学习一门离散的数学课程,这需要我为它写一些简短的代码。这就是我要面对的问题:

开发一个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。

(要解决此测验,请在您的计算机上实现方法更改(数量),在多个输入上进行测试,然后将代码粘贴到下面的字段中并按下提交测验按钮。)

下面是我写的代码:

代码语言:javascript
复制
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’属性)

我不知道发生了什么。请注意,这个类是一个在线类,我正在将代码输入到一个在线平台中,所以我确信算法正在检查某些东西,但我不确定是什么。

EN

回答 3

Stack Overflow用户

发布于 2018-07-22 07:47:05

确保所有返回值都是同一类型的。你需要使用数组,但是当你返回0的时候,你使用的是整型。已修复:

代码语言:javascript
复制
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 
票数 1
EN

Stack Overflow用户

发布于 2018-07-22 17:25:11

谢谢大家!在阅读了您的评论并重新检查了我的错误后,我发现了我逻辑上的错误。如果没有你的帮助,我就不能相应地调整我的想法,我已经重写了下面的代码。我知道这不是最优雅的答案,但我想给出一个在我的Python知识范围内的答案,而不是简单地抄袭别人的工作。话虽如此,看到每个人都是如何解决这个问题的,这让我从另一个角度来看待它。

总而言之,我在逻辑上的错误是忘记了有一种情况,在这种情况下只有7,加或减一个5“硬币”不会解决它。

代码:

代码语言:javascript
复制
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 
票数 1
EN

Stack Overflow用户

发布于 2019-02-23 14:51:48

代码语言:javascript
复制
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)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51460879

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档