【问题标题】:how to refer to the next item in a list and compare it to the item before it?如何引用列表中的下一个项目并将其与之前的项目进行比较?
【发布时间】: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


【解决方案1】:

如果您有 0 或 1 个元素 - 返回 0。 您必须迭代数组的长度,而不是元素本身。两者之间有区别: for i in arrayfor i in range(0,len(array))

小心range - 打开控制台并输入python。检查range(10**2) 打印的内容。它不是一个元素。 https://www.w3schools.com/python/ref_func_range.asp

def count(items):

    if len(items) == 0 or len(items) == 1:
        return 0
    else:
        count = 0
        for i in range(0,len(items)-1):
            items1 = items[i]
            items2 = items[i+1]

            if items1 > items2:
                count = count + 1
        return count

【讨论】:

    【解决方案2】:
    In general
    
    def count_next_test(numbers, test_fn):
      count = 0
      last = len(numbers) - 1
      for i, n in enumerate(numbers):
        if i < last:
          if test_fn(n, numbers[i+1]):
            count += 1
      return count
    

    在你的情况下:count_next_test(numbers, lambda a, b: a

    你也可以这样做

    pairs = zip(numbers, numbers[1:])
    len([(a,b) for a,b in pairs if a < b])
    

    【讨论】:

      猜你喜欢
      • 2014-08-25
      • 2020-10-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多