【问题标题】:Trying to find how often a dice roll result occurs in a list of randomly rolled n-sided dice试图找出掷骰结果在随机掷出的 n 面骰子列表中出现的频率
【发布时间】:2019-03-13 07:43:44
【问题描述】:

我试图找出每个数字的出现次数,从 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()

【问题讨论】:

    标签: python python-3.x random dice


    【解决方案1】:

    最快的方法(我知道)是使用集合中的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})
    

    作为更完整的程序,包括输入 facecount 和 throw-numbers 并进行验证:

    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+] 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

    您正在使用 python 2.x 格式化字符串输出的方式,请阅读format(..) 及其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}
    

    【讨论】:

      【解决方案2】:

      您可以使用dictionary 将其缩小一点。对于骰子之类的东西,我认为一个不错的选择是使用random.choice,然后从你用骰子的侧面填充的列表中绘制。因此,首先,我们可以使用input() 从用户那里收集rolls 和sides。接下来我们可以使用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
      

      【讨论】:

      • 如果您不希望用户输入并且它是为所有用户随机生成的怎么办?
      • @Shakespeareeee 你可以将任何你想要的东西分配给rolls = 和sides = 仍然会起作用
      • 我正在尝试让输出显示“1:x 滚动次数 2:x 滚动次数”等等......我已经坚持了很长时间一会儿。不幸的是,我不知所措。
      猜你喜欢
      • 2021-04-06
      • 1970-01-01
      • 1970-01-01
      • 2017-11-06
      • 2010-10-04
      • 2013-06-12
      • 2019-03-04
      • 1970-01-01
      • 2015-05-10
      相关资源
      最近更新 更多