Python 试图找出随机掷n边骰子列表中掷骰子结果出现的频率
我试图找到每个边的出现次数,从1到骰子上的边数。我希望程序能够找到Python 试图找出随机掷n边骰子列表中掷骰子结果出现的频率,python,python-3.x,random,dice,Python,Python 3.x,Random,Dice,我试图找到每个边的出现次数,从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
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()
随机导入
listRolls=[]
#在6到12之间随机选择骰子的边数
#打印输出“将使用:x边”变量=numSides
def main():
全球裸体
全局numRolls
numSides=边()
numRolls=rolls()
滚动骰子()
计数器输入()
listPrint()
def转鼓():
#对于范围(1)内的转鼓:
###################################
##将20,50更改为200,500##
##
x=(random.randint(20,50))
打印('运行时间为:%s次“%”(x))
打印(“\n”)
返回x
def sides():
#对于范围(1)内的侧面:
y=(random.randint(6,12))
打印(“\n”)
打印('将使用%s边“%”(y))
返回y
def计数器输入()
计数器=[0]*(numSides+1)#未使用计数器[0]。
值=列表卷
#如果value>=1且value最快的方法(据我所知)是使用集合中的计数器()
(仅dict替换请参见底部):
- )是一本专门的字典,它统计你给它的表中出现的次数
- 使用给定的iterable(范围(1,7)==1,2,3,4,5,6)并从中绘制
k
对象,将它们作为列表返回
- 生成一个不可变的序列并使
随机。选择
比使用列表时执行得更好
作为更完整的程序,包括输入人脸计数和带有验证的投掷数字:
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]))
你可以使用字典将其缩小一点。对于骰子之类的东西,我认为一个好的选择是使用随机。选择,然后从填充骰子侧面的列表中进行绘制。因此,首先,我们可以使用输入()从用户那里收集滚动和侧面
。接下来,我们可以使用边
来生成我们从中提取的列表,您可以使用randint
方法来代替此方法,但是对于使用选项
我们可以在范围(1,边+1)中创建一个列表
。接下来,我们可以使用dict
启动一个字典,并制作一个所有边都作为键的字典,值为0
。现在看起来是这样的d={1:0,2:0…n+1:0}
。从这里开始,我们可以使用for
循环来填充我们的字典,将1
添加到滚动的任何一侧。另一个for循环将让我们打印出字典。另外,我加入了max
函数,该函数接收字典中的项目,并根据它们的值对它们进行排序,然后返回l(键,值)
的argesttuple
。然后我们可以打印一个最滚动的语句
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]))
如果您不希望用户输入,而是为所有用户随机生成,该怎么办?@Shakespeareee您可以分配任何您想要的rolls=
,并且sides=
仍将运行sameI,我试图让输出显示“1:x滚动次数2:x滚动次数”诸如此类……我已经坚持了很长一段时间。不幸的是,我不知所措。
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
# 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}
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