问题:
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/