2
def garden(seedList):
  flower = [2, 5, 12]
  flowers = []
  for each in range(len(seedList)):
    totalFlowers = flowers.append(seedList[each] * flower[each])
    x = sum(totalFlowers)
  return totalFlowers

我收到错误:The error was:iteration over non-sequence Inappropriate argument type. An attempt was made to call a function with a parameter of an invalid type. This means that you did something such as trying to pass a string to a method that is expecting an integer.

我需要解决的问题:

编写一个函数,在给定每种花的种子数的情况下计算总花的数量。seedList 参数将包含您拥有的种子数量。每颗种子都会产生一定数量的花朵。一颗矮牵牛种子会开出 2 朵花。一颗雏菊种子会开出 5 朵花。一粒玫瑰种子将产生 12 朵花。每种花的种子。seedList 参数将包含您拥有的种子数量。您应该返回一个整数,其中包含您花园中的鲜花总数。

4

1 回答 1

6

问题是list.append修改列表并返回None

totalFlowers = flowers.append(seedList[each] * flower[each])

所以你的代码实际上是在做:

x = sum(None)

您的代码的工作版本:

def garden(seedList):
  flower = [2, 5, 12]
  flowers = []
  for each in range(len(seedList)):
      flowers.append(seedList[each] * flower[each])

  return sum(flowers)

使用更好的解决方案zip

def garden(seedList):
  flower = [2, 5, 12]
  totalFlowers = sum ( x*y for x,y in zip(flower, seedList) )
  return totalFlowers
于 2013-05-30T00:03:40.723 回答