如何在Python中编写随机投票生成器

时间:2018-10-02 01:35:46

标签: python

因此,我必须编写一个代码,提示用户输入一个数字,即投票者的人数,然后将这些投票者按百分比分配给3个候选人。最重要的是,我必须导入一个随机数,如果该数> = 5,则投票将被视为欺诈并被减去。同样,如果他们受贿,投票将投给其他候选人。最后,我需要使用乌龟制作一个饼图以显示结果。这是我到目前为止所拥有的:

import turtle, random

voters = int(input("Enter the # of would-be voters here: "))

numIM = 0
numCA = 0
numSM = 0

while (voters > 0):
    numIM = random.randint(0,100)
    if numIM <= 5:
        voters -= 1
    numCA = random.randint(0, 100)
    if numCA <= 5:
        voters -= 1
    numSM = random.randint(0, 100)
    if numSM <= 5:
        voters -= 1

令我困惑的部分是: 确定选民将投票支持的英雄。同样,您将使用1到100之间的随机数来确定他们为哪个英雄投票。英雄有以下几率被选中:

钢铁侠-34% 美国队长-33% 蜘蛛侠-33%

2 个答案:

答案 0 :(得分:0)

您可以使用random.choices,它带有可分配给每个项目的参数weights

import random

voters = int(input('Enter the number of would be voters: '))

numIM = 0
numCA = 0
numSM = 0

while (voters > 0):
    vote = random.choices(['im', 'ca', 'sm'], [.34, .33, .33])
    r = random.randint(0, 100)    
    if 'im' in vote:  
        if r <=5:
            numIM -= 1
        else:
            numIM += 1
    elif 'ca' in vote:
        if r <=5:
            numCA -= 1
        else:
            numCA += 1
    elif 'sm' in vote:
        if r <=5:
            numSM -= 1
        else:
            numSM += 1
    voters -= 1

print(numIM, numCA, numSM)
Enter the number of would be voters: 100
25 40 29

答案 1 :(得分:0)

您遇到的问题是三个随机数不能保证总和为100。

这是修改后的版本,但是有效。

import random

voters = int(input('Enter the number of would be voters: '))
voteTypes = {"im":0,"ca":0,"sm":0}
cands = [cand for cand in voteTypes.keys()]
for a in range(voters):
    recip = random.choice(cands)
    voteTypes[recip] +=1