我试图为练习编写代码,虽然它可以正常工作,但它看起来很可怕,我想知道是否有人可以帮助我删除任何不必要的东西,并可能只是组合一些功能?
以下是该函数的使用示例:
choices([['YES', 'NO', 'YES', 'YES'], ['NO', 'NO', 'YES', 'NO'], ['YES', 'YES', 'YES', 'YES']])
列表中的每个列表都有四个是/否选项(下面的索引也列出了四个选项,例如绿色、红色、蓝色、黄色;但不一定是四个)。列表中的列表数量是多少人投票。
i = 0
num = 0
total_num = 0
num_choices = len(INDICES)
choices_index = 0
choices_votes = []
choices_votes_num = []
index = 0
total_choices = []
winning_choice = ''
winning_index = 0
while i < len(parameter):
while num < num_choices:
for item in parameter:
choices_votes.append(item[num])
num += 1
i += 1
while total_num < len(choices_votes):
if choices_votes[total_num] == 'YES':
choices_votes_num.append(1)
total_num += 1
elif choices_votes[total_num] == 'NO':
choices_votes_num.append(0)
total_num += 1
while choices_index < len(choices_votes_num):
count = int(len(choices_votes_num) / num_choices)
total = 0
total = sum(choices_votes_num[choices_index:(choices_index + count)])
total_choices.append(total)
choices_index = choices_index + count
for score in total_choices:
winning_index = max(total_choices)
winning_choice = INDEX_TO_NAME[total_choices.index(winning_index)]
return winning_choice, total_choices
INDEX_TO_NAME
只是一个字典,用于将索引连接到选择(颜色)。
基本上,代码应该将每个“是”计为 1 分,每个“否”计为 0 分,将每个可用选项的总分相加,然后返回总分和获胜者。