[Python] How define the winning candidate in instant runoff voting even if he hasn't the...

Discussão em 'Python' iniciado por Stack, Junho 29, 2025.

  1. Stack

    Stack Membro Participativo

    Hello.


    I'm trying to resolve algorithm of Instant Runoff Voting

    If you haven't heard of it it's an algorithm which choose candidate who has the majority of highest preferences important, active ballots if not it eliminates candidate with the least amount of votes and transfer his votes to the next possible to use, selected preference it it exists.

    In case of complete tie it returns None

    I add first elements from list of lists with candidates (ballots (variable irv)

    # initializing empty list
    fs = []
    # adding first elements of sbublists to variable fs
    for sublist in irv:
    fs.append(sublist[0])


    Then I sorted the most and the lest frequent elements using Counter library.

    most_freq = [item for items, c in Counter(fs).most_common() for item in [items] * c]
    least_freq = [item for items, c in Counter(fs).most_common() for item in [items] * c][-1]


    I removed duplicates using built-in data type set:

    check_freq = set(fs)

    I checked case with tie using if statement:

    if len(check_freq) == len(fs):
    return None


    Then I eliminated last candidate and choose the winner with more than half votes, initialize empty list for the next stage and eliminate last candidate, remove duplicates using built-in data type set.

    sec_choice = most_freq[:-1]
    winner = [item for items, c in Counter(sec_choice).most_common() for item in [items] * c]
    sec_stage = []

    for i in winner:
    if winner[-1] != winner[-2]:
    del winner[-1]
    check_same = set(winner)


    Final step is checking the length of set and choose winner from the rest of the candidates.

    if len(check_same) == 1:
    return ''.join(check_same)
    else:
    if winner[-1] != winner[-2]:
    del winner[-1]

    return winner[-1]


    Unfortunately it doesnt work for random input. How can I define the winning candidate in described case?

    Can you help me with this algorithm?

    Continue reading...

Compartilhe esta Página