简体   繁体   中英

How to count the number of times a number in a list is greater than the number after it?

I want to see the number of times that a number is greater than the number after it, in a list.

example = [2, 3, 4, 5, 7, 8, 6, 2, 3, 4, 5]

def lstCount(lst):
    counter = 0
    if lst[0] < lst[1]:
        counter + 1 
        lstCount(lst[1:])
    else:
        lstCount(lst[1:])

    return counter

lstCount(example)

This should produce 2, but I am getting list index out of range.

it = iterator(lst)
next(it, None)
count = sum(a > b for a, b in zip(lst, it))

Or simply

count = sum(a > b for a, b in zip(lst, lst[1:]))

You need to add a base case where the lst is only 1 element. Otherwise when it checks lst[1] it will be attempting to check an element that does not exist and you can get an out of bounds error. Additionally counter + 1 does nothing. I suggest simply returning the value instead of using a counter.

def lstCount(lst):
    if len(lst) == 1:
        return 0
    elif lst[0] > lst[1]:
        return 1 + lstCount(lst[1:])
    return lstCount(lst[1:])

Another straight solution: traverse first n-1 elements and compare current and next element in list.

example = [2, 3, 4, 5, 7, 8, 6, 2, 3, 4, 5]
count = 0
for i in range(len(example) - 1):#get size of example then decrease by 1
    if example[i] < example[i + 1]:#visit element by index
        count = count + 1
print count

Output:
8

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM