morveine
morveine

Reputation: 1

Iterate and compare nth element with the rest of elements in list

I have a list of integers and have to check if all of the integers to the right (so, from each int to the end of the list) are strictly smaller than the one I'm iterating over.

E.g. for [42, 7, 12, 9, 2, 5] I have to compare if 42 is bigger than [7, 12, 9, 2, 5], if 7 is bigger than [12, 9, 2, 5] and so on to the end of the list.

The function has to return the amount of numbers that are bigger than the rest of the list, including the last one - as there's no bigger number after it.

Code I have now:

def count_dominators(items):

    if len(items)< 2:
        return len(items)
    

    dominators_count = 0
    for ind, el in enumerate(items[0:-1]):
        
        if el > items[ind+1]:
            dominators_count += 1
            pass

I've tried iterating with nested for-loops, using enumerate() and iterating over that using itertools.combinations(), and combining those ways, but to no avail - I usually get TypeErrors linked to iterating (e.g list index out of range, even though I used slicing to avoid it).

Upvotes: 0

Views: 131

Answers (1)

Samwise
Samwise

Reputation: 71454

I'd suggest using enumerate to iterate over the items with their indices (as you're already doing), and then using all to iterate over all the items after a given item, and sum to sum all of the all results:

>>> def count_dominators(items):
...     return sum(all(n > m for m in items[i+1:]) for i, n in enumerate(items))
...
>>> count_dominators([42, 7, 12, 9, 2, 5])
4

Another approach would be to compare to the max of the remaining items, although then you need to special-case the end of the list (all returns True for an empty list, but max will raise an exception):

>>> def count_dominators(items):
...     return sum(n > max(items[i+1:]) for i, n in enumerate(items[:-1])) + 1
...
>>> count_dominators([42, 7, 12, 9, 2, 5])
4

Upvotes: 1

Related Questions