试图找出随机掷骰结果在随机掷出的nsided di列表中发生的频率

2024-10-02 00:29:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我试着找出每个边数的出现次数,边数是1到骰子掷骰子的边数。我希望程序找到listRolls中每个数字的出现次数。在

例如:如果有一个6面骰子,那么它将是1到6,列表将掷骰子x数量,我想知道骰子掷了多少次1,以此类推。在

我是python新手,正在努力学习它!任何帮助都将不胜感激!在

import random
listRolls = []

# Randomly choose the number of sides of dice between 6 and 12
# Print out 'Will be using: x sides' variable = numSides
def main() :
   global numSides
   global numRolls

   numSides = sides()
   numRolls = rolls()

rollDice()

counterInputs()

listPrint()


def rolls() :
#    for rolls in range(1):
###################################
##    CHANGE 20, 50 to 200, 500  ##
##
    x = (random.randint(20, 50))
    print('Ran for: %s rounds' %(x))
    print ('\n')
    return x

def sides():
#    for sides in range(1):
    y = (random.randint(6, 12))
    print ('\n')
    print('Will be using: %s sides' %(y))
    return y

def counterInputs() :
    counters = [0] * (numSides + 1)   # counters[0] is not used.
    value = listRolls

#    if value >= 1 and value <= numSides :
#         counters[value] = counters[value] + 1

for i in range(1, len(counters)) :
  print("%2d: %4d" % (i, value[i]))

print ('\n')

#  Face value of die based on each roll (numRolls = number of times die is 
thrown).
#  numSides = number of faces)
def rollDice():     
    i = 0
    while (i < numRolls):
        x = (random.randint(1, numSides))
        listRolls.append(x)
#            print (x)   
        i = i + 1
#        print ('Done')

def listPrint():
    for i, item in enumerate(listRolls):
        if (i+1)%13 == 0:
            print(item)
    else:
        print(item,end=', ')
print ('\n')





main()

Tags: ofinnumberforvaluedefrandom骰子
2条回答

最快的方法(据我所知)是从集合中使用Counter()(仅dict替换见底部):

import random

from collections import Counter

# create our 6-sided dice
sides = range(1,7)  
num_throws = 1000

# generates num_throws random values and counts them
counter = Counter(random.choices(sides, k = num_throws))

print (counter) # Counter({1: 181, 3: 179, 4: 167, 5: 159, 6: 159, 2: 155})
  • ^{})是一个专门的字典,它统计给定的iterable中出现的次数。

  • ^{}使用给定的iterable(范围(1,7)==1,2,3,4,5,6并从中提取k个东西,并将它们作为list返回。

  • ^{}生成一个不可变的序列,使random.choices的性能比使用列表时更好。


作为更完整的程序,包括输入面数和投掷数,并进行验证:

^{pr2}$

输出:

How many sides on the dice? [4+] 1
Try gain, number must be 4 or more  

How many sides on the dice? [4+] a
Try gain, number must be 4 or more  

How many sides on the dice? [4+] 5
How many throws? [1+] -2
Try gain, number must be 1 or more  

How many throws? [1+] 100    

Number 1 occured 22 times
Number 2 occured 20 times
Number 3 occured 22 times
Number 4 occured 23 times
Number 5 occured 13 times

您正在使用python2.x方式格式化字符串输出,请阅读关于^{}及其format examples的内容。在

看看验证来自用户的输入的非常好的答案:Asking the user for input until they give a valid response


如果不允许使用Counter,请替换它:

# create a dict
d = {}

# iterate over all values you threw
for num in [1,2,2,3,2,2,2,2,2,1,2,1,5,99]:
    # set a defaultvalue of 0 if key not exists
    d.setdefault(num,0)
    # increment nums value by 1
    d[num]+=1

print(d)  # {1: 3, 2: 8, 3: 1, 5: 1, 99: 1}

您可以使用dictionary将其稍微缩小一点。对于像骰子这样的东西,我认为一个好的选择是使用random.choice并从一个用骰子边填充的列表中绘制。首先,我们可以使用input()从用户那里收集rolls和{}。接下来,我们可以使用sides来生成我们从中提取的列表,您可以使用randint方法来代替它,但是对于使用choice我们可以在range(1, sides+1)中生成一个列表。接下来,我们可以使用dict初始化一个字典,并创建一个所有边都作为键的字典,其值为0。现在看起来是d = {1:0, 2:0...n+1:0}。从这里开始,我们可以使用一个for循环来填充我们的字典,将1添加到滚动的任何一边。另一个for循环将让我们打印出字典。奖金。我抛出了一个max函数,该函数接受dictionary中的项,并按它们的values对它们进行排序,并返回(key, value)中最大的tuple。然后我们就可以打印一份最全面的报表。在

from random import choice

rolls = int(input('Enter the amount of rolls: '))
sides = int(input('Enter the amound of sides: '))
die = list(range(1, sides+1))
d = dict((i,0) for i in die) 

for i in range(rolls):
    d[choice(die)] += 1

print('\nIn {} rolls, you rolled: '.format(rolls))
for i in d:
    print('\tRolled {}: {} times'.format(i, d[i]))

big = max(d.items(), key=lambda x: x[1])
print('{} was rolled the most, for a total of {} times'.format(big[0], big[1]))
Enter the amount of rolls: 5
Enter the amound of sides: 5

In 5 rolls, you rolled: 
  Rolled 1: 1 times
  Rolled 2: 2 times
  Rolled 3: 1 times
  Rolled 4: 1 times
  Rolled 5: 0 times
2 was rolled the most, for a total of 2 times

相关问题 更多 >

    热门问题