You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

投票系统脚本出现IndexError问题求助及代码优化建议

Understanding the Error & Improving Your Voting System Script

First, let's break down the error you're seeing:
IndexError: list index out of range happens because your code hardcodes references to indexes 0 through 3 (assuming exactly 4 candidates), but your votes list likely has fewer than 4 elements. For example, if there are only 2 candidates, votes[3] doesn't exist—lists in Python are zero-indexed, so the last valid index is always len(votes) - 1.

A More Robust & Concise Implementation

Instead of writing repetitive conditionals tied to 4 candidates (which breaks easily if you add/remove candidates), let's rewrite the function to handle any number of candidates dynamically:

def get_winner(votes, cands):
    if not votes or not cands:
        print("No votes or candidates provided.")
        return
    
    max_vote_count = max(votes)
    # Collect all candidates who received the maximum votes
    winning_candidates = [
        candidate for idx, candidate in enumerate(cands) 
        if votes[idx] == max_vote_count
    ]
    
    if len(winning_candidates) > 1:
        print(f"We have a tie between: {', '.join(winning_candidates)}")
    else:
        print(f"Congratulations candidate {winning_candidates[0]}! You win")

Key Improvements:

  • Flexible Candidate Support: Works for any number of candidates (1, 4, 10, etc.) instead of being locked to 4.
  • Eliminates Redundancy: No more repetitive if statements for each candidate or redundant tie checks (your original code had 4 identical tie conditions).
  • Error Prevention: Added a check for empty votes or cands lists to avoid unexpected crashes.
  • Readability: Uses list comprehension to cleanly collect winners, making the logic straightforward to follow.

Example Usage:

# Test with 4 candidates (your original scenario)
votes = [15, 22, 18, 22]
cands = ["Alice", "Bob", "Charlie", "Diana"]
get_winner(votes, cands)  # Output: "We have a tie between: Bob, Diana"

# Test with 2 candidates
votes = [30, 25]
cands = ["Eve", "Frank"]
get_winner(votes, cands)  # Output: "Congratulations candidate Eve! You win"

This approach is far more maintainable and avoids the index error entirely because it never assumes a fixed number of candidates.

内容的提问来源于stack exchange,提问作者C Plant

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:40:22