MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / majority_vote

Function majority_vote

other/majority_vote_algorithm.py:11–32  ·  view source on GitHub ↗

>>> majority_vote([1, 2, 2, 3, 1, 3, 2], 3) [2] >>> majority_vote([1, 2, 2, 3, 1, 3, 2], 2) [] >>> majority_vote([1, 2, 2, 3, 1, 3, 2], 4) [1, 2, 3]

(votes: list[int], votes_needed_to_win: int)

Source from the content-addressed store, hash-verified

9
10
11def majority_vote(votes: list[int], votes_needed_to_win: int) -> list[int]:
12 """
13 >>> majority_vote([1, 2, 2, 3, 1, 3, 2], 3)
14 [2]
15 >>> majority_vote([1, 2, 2, 3, 1, 3, 2], 2)
16 []
17 >>> majority_vote([1, 2, 2, 3, 1, 3, 2], 4)
18 [1, 2, 3]
19 """
20 majority_candidate_counter: Counter[int] = Counter()
21 for vote in votes:
22 majority_candidate_counter[vote] += 1
23 if len(majority_candidate_counter) == votes_needed_to_win:
24 majority_candidate_counter -= Counter(set(majority_candidate_counter))
25 majority_candidate_counter = Counter(
26 vote for vote in votes if vote in majority_candidate_counter
27 )
28 return [
29 vote
30 for vote in majority_candidate_counter
31 if majority_candidate_counter[vote] > len(votes) / votes_needed_to_win
32 ]
33
34
35if __name__ == "__main__":

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected