Plurality选举程序多位获胜者输出异常问题及代码修改求助
Fixing Plurality Election Tie Handling
Let's get your election program working correctly when there's a tie for first place! The core issue with your current code is that it only picks the first candidate who hits the maximum vote count, but we need to identify all candidates who share that top number of votes.
Here's the revised code with tie support:
candidate_number = int(input("Number of candidates: ")) while candidate_number <= 0: candidate_number = int(input("Number of candidates: ")) candidates = [] for i in range(candidate_number): a = input("Candidate: ").upper() while a in candidates: a = input("Candidate: ").upper() candidates.append(a) print("") voter_number = int(input("Number of voters: ")) while voter_number <= 0: voter_number = int(input("Number of voters: ")) votes = [] for i in range(voter_number): a = input("Vote: ").upper() votes.append(a) # Calculate vote counts for each candidate (more efficient than repeated count() calls) vote_counts = {candidate: votes.count(candidate) for candidate in candidates} # Find the highest number of votes max_votes = max(vote_counts.values()) # Collect all candidates who have the maximum votes winners = [candidate for candidate, count in vote_counts.items() if count == max_votes] # Print results appropriately print("\n" * 3) if len(winners) > 1: print("Winners: " + ", ".join(winners)) else: print("Winner: " + winners[0])
Key improvements explained:
- Efficient Vote Counting: We use a dictionary (
vote_counts) to map each candidate to their total votes in one pass per candidate, which is way more efficient than your original approach of callingvotes.count()for every single vote entry. - Tie Detection: Instead of grabbing just the first candidate with max votes, we filter all candidates to find everyone who matches the highest vote count.
- Dynamic Output: We check if there's one winner or multiple, and adjust the output text ("Winner" vs "Winners") accordingly, joining multiple winners with commas for clean readability.
Example Output for a Tie:
If candidates ALICE, BOB, and CHARLIE each get 5 votes, the program will output:
Winners: ALICE, BOB, CHARLIE
This should handle all cases correctly, whether there's a single winner or a multi-way tie!
内容的提问来源于stack exchange,提问作者Anay Garodia
相关产品推荐
相关产品推荐

