0

The example of my problem, so I don't have to put the entire code in here is the following.

def mandatos(nr_votes):
    nr_candidates = len(nr_votes)
    candidate_with_most_votes = max(nr_votes)

    print (nr_candidates)
    print (candidate_with_most_votes)

    >>> mandatos((10, 8, 6)
    >>> 3
    >>> 10

This is what I've written on secondary python file to see if these would work on my main file. What I am missing on my main file to keep on using the retrieved data on my function is to know the position of '10' in this example. I know on this case that it's on position 0, just by checking. But the program itself I am building is going to have dozens of entrys in a tuple and after reading the maximum element within the tuple, i'll have to give a mandate? to the highest voted candidate and then knowing the position of the most voted candidate, divide it's votes by the next divisor.

Sagar Rakshe
  • 2,682
  • 1
  • 20
  • 25
  • `nr_votes.index(max(nr_votes))` will give the index of the highest number in the tuple. If there are 2 the same, e.g. 2 times 10, then it will only return the index of the first 10 – Tim Oct 15 '15 at 09:19
  • Thanks for all the fast reply. –  Oct 15 '15 at 11:42

2 Answers2

3

[CORRECTED:]

A Pythonic way would be

candidate_with_most_votes = max(enumerate(nr_votes), key=lambda x: x[1])[0]

Or, if you want the vote count also,

vote_count, candidate_with_most_votes = max(enumerate(nr_votes), key=lambda x: x[1])

max (like many other functions) allows you to specify a "key" function that's used to extract the value to compare from each element in the tuple. Enumerate yields a tuple of (idx, item) for every item in an iterable. Combining these two, you get what you want.

EXAMPLE:

>>> a=[10,30,20]
>>> max(enumerate(a), key=lambda x: x[1])[0]
1
>>> for i, item in enumerate(a): print(i,item)
(0, 10)
(1, 30)
(2, 20)
peak
  • 105,803
  • 17
  • 152
  • 177
shash
  • 965
  • 8
  • 16
0

If I understood correctly, you want the position of the max. Try:

candidate_index = nr_votes.index(candidate_with_most_votes)
Charlotte45
  • 143
  • 1
  • 16