gpt4 book ai didi

python - 尝试找出随机滚动的 n 面骰子列表中掷骰子结果出现的频率

转载 作者:行者123 更新时间:2023-12-01 08:57:24 25 4
gpt4 key购买 nike

我试图找到从 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()

最佳答案

最快的方法(我知道)是使用集合中的 Counter() (参见底部的仅字典替换):

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})
<小时/>

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

def inputNumber(text,minValue):
"""Ask for numeric input using 'text' - returns integer of minValue or more. """
rv = None
while not rv:
rv = input(text)
try:
rv = int(rv)
if rv < minValue:
raise ValueError
except:
rv = None
print("Try gain, number must be {} or more\n".format(minValue))
return rv


from collections import Counter
import random

sides = range(1,inputNumber("How many sides on the dice? [4+] ",4)+1)
num_throws = inputNumber("How many throws? [1+] ",1)
counter = Counter(random.choices(sides, k = num_throws))

print("")
for k in sorted(counter):
print ("Number {} occured {} times".format(k,counter[k]))

输出:

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

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

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

How many throws? [1+] <b>100</b>

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

您正在使用 python 2.x 方式格式化字符串输出,请阅读 format(..)及其 format examples .

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

<小时/>

如果您不允许使用计数器,请更换它:

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

关于python - 尝试找出随机滚动的 n 面骰子列表中掷骰子结果出现的频率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52705611/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com