ah789
ah789

Reputation: 29

Check how many adjacent numbers are bigger than the previous in a list?

I'm fairly new to python and cannot figure out how to check if an adjacent number is bigger than the previous, and do this with every number along the list L. This is what i've tried but it only outputs the total number of elements in the list:

def adjacent(L)
    sum = 0
    for i in L:
        if [i] < [i + 1] :
            sum = sum + 1
    print(sum)

Upvotes: 1

Views: 1069

Answers (3)

Padraic Cunningham
Padraic Cunningham

Reputation: 180550

Index the list with each i using range, you are comparing each i and i + 1 wrapped in lists not the actual list elements:

def adj(l):
    return sum(l[i] < l[i+1] for i in range(len(l)-1))

You would also want to catch lists with 1 or 0 elements:

def adj(l):
    return 0 if len(l) < 2 else sum(l[i] < l[i+1] for i in range(len(l)-1))

You could also use itertools.tee to create you pairs:

from itertools import tee


def adj(l):
    a, b = tee(l)
    next(b, None)
    return sum(a < b for a, b in zip(a, b))

Upvotes: 1

Raphael Passini Diniz
Raphael Passini Diniz

Reputation: 11

There seems to be an error in your logic. In your "if" statement you're comparing two lists, both with 1 number.

Here is how I would write it:

def find_bigger_adjacents(mylist):
    adjacents = []

    # the first previous number is the first element of the list
    prev = mylist[0]

    # I want to interact over all elements but first
    for x in mylist[1:]:
        if x > prev:
            adjacents.append((prev, x))
        prev = x

    return prev

Upvotes: 0

Kasravnd
Kasravnd

Reputation: 107357

In following part:

[i] < [i + 1]

You are putting the list items in list and add 1 to one of them and compare them which is wrong.

If you want to access to previous item of each item you need to decrease it's index 1 unit and access to its relative item by a simple indexing like L[1] which will gives you the second items of your list.

Also as a more pythonic way for accessing to all pair of a list items you can use zip function.For example:

>>> L=range(7)
>>> L
[0, 1, 2, 3, 4, 5, 6]
>>> 
>>> zip(L,L[1:])
[(0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (5, 6)]

Note: in pyhton 3.X zip returns an iterator (which doesn't makes any different when you want to loop over the result).

And then you can loop over the result like following:

for i,j in zip(L,L[1:]):
    # do something 

And finally about your task since you want to count the number of this pairs which the second items is larger than the first you can use a generator expression within sum function:

sum(j>i for i,j in zip(L,L[1:]))

Note that since the result of j>i is a boolean value and python will evaluate the True as 1 and False as 0 at the end it will comes up with the expected count of those pairs that follow your criteria.

Upvotes: 3

Related Questions