Python:值的总和大于最后一个值

标签 python list

问题:

Write a program that will loop through a list and sum all values greater than the last value in the list. If there are no values greater than the list or if the list is empty, return -1.

我的代码:

def go(list1):
    total = 0
    count = 0
    for i in range(0,len(list1)-1):
        if list1[i] < list1[i+1]:
            total+=list1[i+1]
            count += 1
        else:
            total += 0
        if count is 0:
            total = -1
        if len(list1) == 1:
            total = -1
    return total

print(go( [-99,1,2,3,4,5,6,7,8,9,10,5] ))
print(go( [10,9,8,7,6,5,4,3,2,1,-99] ))
print(go( [10,20,30,40,50,-11818,40,30,20,10] ))
print(go( [32767] ))
print(go( [255,255] ))
print(go( [9,10,-88,100,-555,2] ))
print(go( [10,10,10,11,456] ))
print(go( [-111,1,2,3,9,11,20,1] ))
print(go( [9,8,7,6,5,4,3,2,0,-2,6] ))
print(go( [12,15,18,21,23,1000] ))
print(go( [250,19,17,15,13,11,10,9,6,3,2,1,0] ))
print(go( [9,10,-8,10000,-5000,-3000] ))

我的输出:

55
-1
180
0
-1
112
466
46
5
1077
-1
7010

期望的输出:

55
-1
180
-1
-1
112
466
46
5
1077
-1
7010

我做错了什么?为什么输出是 0 而不是 -1?

最佳答案

当您放入的列表的长度为 1 时,您将遍历 for 循环零次。

这意味着您放入其中检查条件的任何代码将永远不会被执行。我个人希望尽快返回,因此我建议如下:

def go(list1):
  if len(list1) == 1:
      return -1
  total = 0
  count = 0
  for i in range(0,len(list1)-1):
      if list1[i] < list1[i+1]:
          total+=list1[i+1]
          count += 1
  if count is 0:
      return -1
  return total

关于Python:值的总和大于最后一个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50050795/

相关文章:

python - 有没有办法在 emacs 中获得更好的终端?

python - 检查数字列表是否在特定范围内?

python - Pylint 说 : W0233: __init__ method from a non direct base class 'Nested' is called (non-parent-init-called)

python - 相当于PyQt/PySide中wxPython的Freeze and Thaw

python - 在 Python 中读取 .mat 文件。但是数据的形状发生了变化

python - 在 Python 中 append 关联数组

Java 原始类型(例如 List 与 List<Object> )

python - 从 NumPy 数组的每一行中删除一个元素

Java:将整数数组划分为具有随机值的子数组?

list - 迭代后的Python zip对象 'disappears'?