问题:
编写一个循环遍历列表的程序,并将所有大于最后的值相加 列表中的值。如果没有大于列表的值或列表为空,则返回-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?
答案 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
答案 1 :(得分:1)
经验法则:请务必首先检查转角情况,然后再进行进一步处理
def go(list1):
total = 0
# no need for extra int variable, bool will do the job.
greater_found = False
# this condition will cover for list with single or no(empty list) element
if len(list1) < 2:
return -1
for i in range(1, len(list1)):
if list1[i] > list1[i-1]:
total = total + list1[i]
greater_found = True
if not greater_found:
return -1
return total