我是python和编程的新手。我正在尝试创建一个骰子模拟器,允许用户选择骰子有多少边以及掷骰子多少次。然后程序应该跟踪每个数字出现的次数并显示结果。
我已经做到这一点,随机数生成器将为每个卷生成一个随机数。但我无法弄清楚如何跟踪每个数字出现的次数并显示出来。请帮忙:
# dice simple
import random
x = input ("How many sides does you dice have?")
y = input ("How many times do you want to roll?")
for i in range (y):
z = random.randint (1, x)
答案 0 :(得分:2)
defaultdict
非常适合:
from collections import defaultdict
d = defaultdict(int)
d[1] += 1
d[6] += 1
d[1] += 1
print(d)
defaultdict(<type 'int'>, {1: 2, 6: 1})
答案 1 :(得分:1)
from collections import Counter
import sys
from random import randint
# Python 2/3 compatibility
if sys.hexversion >= 0x3000000:
inp = input
rng = range
else:
inp = raw_input
rng = xrange
def get_int(prompt):
while True:
try:
return int(inp(prompt))
except ValueError:
pass
def main():
sides = get_int("How many sides does your die have? ")
times = get_int("How many times do you want to roll? ")
results = Counter(randint(1, sides) for roll in rng(times))
if __name__=="__main__":
main()
答案 2 :(得分:0)
# dice simple
import random
x = input ("How many sides does you dice have?")
y = input ("How many times do you want to roll?")
for i in range (y):
z = random.randint (1, x)