summing the dice trials and histogram plot

前端 未结 3 1793
终归单人心
终归单人心 2021-01-28 03:21

I am stuck in a code in python which takes in number of dices and number of rolls and returns the sum of numbers obtained. It should also print the histogram of the sum. I am st

3条回答
  •  执笔经年
    2021-01-28 03:54

    Your problem here is that you can't arbitrarily index into an empty list:

    l = []
    l[13] += 1 # fails with IndexError
    

    Instead, you could use a defaultdict, which is a special type of dictionary that doesn't mind if a key hasn't been used yet:

    from collections import defaultdict
    d = defaultdict(int) # default to integer (0)
    d[13] += 1 # works fine, adds 1 to the default
    

    or Counter, which is designed for cases like this ("provided to support convenient and rapid tallies") and provides extra handy functions (like most_common(n), to get the n most common entries):

    from collections import Counter
    c = Counter()
    c[13] += 1
    

    To manually use a standard dict to do this, just add a check:

    d = {}
    if 13 in d: # already there
        d[13] += 1 # increment
    else: # not already there
        d[13] = 1 # create
    

提交回复
热议问题