user1487497
user1487497

Reputation: 2293

How do I compare one index to the previous index within the same list?

I'm trying to make this program look at each previous number in a list, and determine if that number is bigger than it. If it is, it should record how many times bigger, and return it at the end. i.e. the count (I'm using num as the variable) starts at 0. But 10 is bigger than 7 so num becomes 1. Now 7 isn't bigger than 20 so the count stays the same. but 20 is bigger than 15 so the count (num) is 2. and 15 is bigger than 4 (count is 3). Now 4 is not bigger than 6 (count does not change) and 6 is not bigger than the next number because there is no next number. This is what I have now. I'm thinking lst[i] and lst[i+1] need to be used to reference index maybe? Can anyone walk me through this? Thanks.

def count(lst):
num = 0 
some sort of division here? then add to num variable?

#main prog
( count([10, 7, 20, 15, 4, 6]) ) 

Upvotes: 1

Views: 253

Answers (4)

Hugh Bothwell
Hugh Bothwell

Reputation: 56654

From the itertools recipes:

from itertools import tee, izip

def pairwise(iterable):
    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
    a, b = tee(iterable)
    next(b, None)
    return izip(a, b)

def count(lst):
    return sum(a>b for a,b in pairwise(lst))

then

count([10, 7, 20, 15, 4, 6])  # => 3

Upvotes: 0

inspectorG4dget
inspectorG4dget

Reputation: 113965

Try this:

def count(lst):
    answer = 0
    for i,num in enumerate(lst[1:], 1):
        answer += num < lst[i-1]
    return answer

It turns out that adding boolean values to integers forces the bools to be treated as ints as well (True is 1 and False is 0). So you can use that to make more readable code.

Hope this helps

Upvotes: 1

tacaswell
tacaswell

Reputation: 87376

import numpy as np
def count(lst):
    return sum(np.diff(lst)>0)

diff gives the difference between successive elements, the sum returns the number of positive differences.

Upvotes: 2

Ned Batchelder
Ned Batchelder

Reputation: 375584

def count(lst):
    return sum(i > j for i,j in zip(lst[:-1], lst[1:]))

Here we zip together the list, offset by one, to get the consecutive pairs. Then we compare each pair. Booleans are integers, so we can sum them to produce the final count.

Upvotes: 1

Related Questions