在Python中创建骰子模拟器,如何找到最常见的骰子

时间:2018-09-04 19:15:19

标签: python python-3.x data-structures

import random
#Making sure all values are = to 0
one = 0
two = 0
three = 0
four = 0
five = 0
six = 0

#Loop for rolling the die 100 times
for r in range(0, 100):
    roll = random.randint(1, 6)
    if roll == 1:
        one += 1
    elif roll == 2:
        two += 1
    elif roll == 3:
        three += 1
    elif roll == 4:
        four += 1
    elif roll == 5:
        five += 1
    elif roll == 6:
        six += 1

#print how many times each number was rolled
print(one)
print(two)
print(three)
print(four)
print(five)
print(six)

#How many times the 3 was rolled
print("The 3 was rolled", three, "times!")

#Average roll between all of them
print("The average roll was", (one * 1 + two * 2 + three * 3 + 4 * four + 5 * five + 6 * six)/100)

我正在尝试使其打印出来

“数字是最常见的纸卷。”无论哪个卷。

仅尝试执行此操作是最简单的方法,而我对如何执行操作感到困惑。我试图做一下,如果一个>两个>三个等,但那没有用。

1 个答案:

答案 0 :(得分:1)

选择适当的数据结构以最大程度地利用语言的核心功能,是程序员可以开发的最有价值的技能之一。

对于此特定用例,最好使用可迭代的数据类型,以简化对数字集合的操作(例如排序,获取最大值)。由于我们想将数字(1-6)与该数字的滚动次数相关联,因此字典似乎是最简单的数据结构选择。

我已经重新编写了该程序,以展示如何使用字典作为其数据结构来重新实现其现有功能。加上注释,代码应该是不言自明的。

棘手的部分是这个问题实际上要问的问题:确定最常滚动的数字。除了手动实现排序算法外,我们还可以使用Python内置的max function。它可以接受可选的key参数,该参数指定在执行比较之前应应用于可迭代对象中每个项目的函数。在这种情况下,我选择了dict.get()方法,该方法返回与键对应的值。这就是将掷骰结果字典与每个结果的掷骰数进行比较以确定最频繁掷骰的数量的方法。请注意,max()仅返回一项,因此在平局的情况下,将仅打印其中一项结果(请参见Which maximum does Python pick in the case of a tie?)。

另请参阅:How do I sort a dictionary by value?

import random

NUM_ROLLS = 100
DIE_SIDES = 6

# Create the dictionary to store the results of each roll of the die.
rolls = {}

#Loop for rolling the die NUM_ROLLS times
for r in range(NUM_ROLLS):
    roll_result = random.randint(1, DIE_SIDES)
    if roll_result in rolls:
        # Add to the count for this number.
        rolls[roll_result] += 1
    else:
        # Record the first roll result for this number.
        rolls[roll_result] = 1

# Print how many times each number was rolled
for roll_result in range(1, 7):
    print("The number", str(roll_result), "was rolled", str(rolls[roll_result]), "times.")

#How many times the 3 was rolled
print("The number three was rolled", str(rolls[3]), "times.")

#Average roll between all of them
sum = 0
for roll_result in rolls:
    sum += roll_result * rolls[roll_result]
print("The average roll result was", str(sum/NUM_ROLLS))

# The number rolled most often.
print(str(max(rolls, key=rolls.get)), "is the most common roll result.")