Reputation: 37
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.
Upvotes: 0
Views: 179
Reputation: 333
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
Upvotes: 0
Reputation: 1609
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:])
Upvotes: 0
Reputation: 45542
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:]))
Upvotes: 4