【发布时间】:2019-11-21 20:29:06
【问题描述】:
我有一个作业问题,它要求制定一个算法,该算法将遍历列表中的每个元素,看看它旁边的数字是否大于当前数字。如果它不大于当前数字,则计数器将增加 1,如果大于则计数器将保持原位。 我让它工作了,但它只有在列表中有超过 3 个项目时才有效。
这是我目前所拥有的:
def count(items):
if len(items) == 0:
return 0
else:
count = 0
for i in items:
count += 1
items1 = items[i:]
items2 = items[i+1:]
if items1 > items2:
return count - 1
print (count([42, 7, 12, 9, 2, 5])) #returns 4. works but does not work if len < 3
print (count([])) #returns 0. works
print (count(list(range(10**7)))) # supposed to print out 1 since it's only 1 number, but it just gets stuck and doesn't finish the rest of the program
print (count([99])) # prints out none
print (count(list(range(10**7,0,-1))))# supposed to print out 10000000 but prints 1 instead
任何形式的帮助或建议将不胜感激。
【问题讨论】:
-
算法语句很奇怪。什么是“当前数字”,计数还是当前元素?假设当前数字,那么第一个答案将是 2,因为 12 > 7 和 5 > 2。
标签: python python-3.x for-loop if-statement