Unlimited sides to dice in simulator

2019-09-02 10:16发布

I am new to python and programming in general. I am trying to create a dice simulator that will allow the user the choose how many sides the dice has and how many times to roll the dice. Then the program is supposed to keep track of how many times each number comes up and display the result.

I have gotten this far, where the random number generator will generate a random number for each roll. But i can't figure out how to track the number of times each number comes up and display that. Please help:

# 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)

3条回答
你好瞎i
2楼-- · 2019-09-02 10:21
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()
查看更多
时光不老,我们不散
3楼-- · 2019-09-02 10:22
# 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)
查看更多
不美不萌又怎样
4楼-- · 2019-09-02 10:24

defaultdict fits nicely:

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})
查看更多
登录 后发表回答