如何在多人选举程序中打印多个获胜者



我正在尝试创建一个模拟多人选举的程序。当有一个赢家时,代码运行良好,但当有一场平局并且有多个赢家时就会被卡住。我尝试使用if-elif循环,但它没有按预期工作。如果您能够修改代码使其工作,那将是非常有帮助的。

candidate_number = int(input("Number of candidates: "))
while candidate_number <= 0:
candidate_number = int(input("Number of candidates: "))
candidates = []
votes = []
find = []
tie = []

for i in range(1, 1 + candidate_number):
a = input("Candidate: ").upper()
while a in candidates:
a = input("Candidate: ").upper()
else:
candidates.append(a)
print("")
voter_number = int(input("Number of voters: "))
while voter_number <= 0:
voter_number = int(input("Number of voters: "))

for i in range(1, 1 + voter_number):
a = input("Vote: ").upper()
votes.append(a)
for i in range(len(votes)):
find.append(votes.count(votes[i]))
k = find.index(max(find))
for i in range(3):
print("")
print("Winner: " + votes[k])

如果只有一个最大值,则可以

if find.count(max(find)) == 1:

然后使用您的旧方法(针对单个冬季(或for-循环来显示所有获胜者。

max_count = max(find)
for c in candidates:
if votes.count(c) == max_count:
print('MAX VOTES:', c)

最小工作代码

votes = ['A', 'B', 'A', 'Mr. X', 'B', 'C', 'D', 'C']
candidates = sorted(set(votes))  # create list of candidates base on votes
find = []
# display all candidates
print('--- candidates ---')
for c in candidates:
print(c)
# count votes and also display it 
print('--- count votes ---')
for c in candidates:
count = votes.count(c)
find.append(count)
print(c, ':', count)

# find max count  
print('--- max ---')
max_count = max(find)
print('max_count:', max_count)
print('nn--- results ---nn')
# check if only one max count
if find.count(max_count) == 1:
# display winner
index = find.index(max(find))
print('Winner:', votes[index])
else:
# display all 
for c in candidates:
if votes.count(c) == max_count:
print('Draw:', c)

编辑:x2

if find.count(max_count) == 1:
# ... code ...
else:
# display all 
# --- before loop ---
all_winners = []
# --- loop ---
for c in candidates:
if votes.count(c) == max_count:
all_winners.append(c)
# --- after loop ---        
print('Draw:', ",".join(all_winners) )

最新更新