1

I am trying to find the occurrences of each number for sides going 1 up to the number of sides on a dice roll. I would like the program to find the number of occurrences for each number that is in listRolls.

Example: if there were a 6 sided dice then it would be 1 up to 6 and the list would roll the dice x amount of times and I would like to find how many times the dice rolled a 1 so on and so forth.

I am new to python and trying to learn it! Any help would be appreciated!

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()
Patrick Artner
  • 50,409
  • 9
  • 43
  • 69

2 Answers2

1

Fastest way (I know of) is using Counter() from collections (see bottom for dict-only replacement):

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

As more complete program including inputting facecount and throw-numbers with validation:

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

Output:

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

You are using python 2.x way of formatting string output, read about format(..) and its format examples.

Take a look at the very good answers for validating input from user: Asking the user for input until they give a valid response


Replacement for Counter if you aren't allowed to use it:

# 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}
Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
0

You could trim this down a bit using a dictionary. For stuff like dice I think a good option is to use random.choice and just draw from a list that you populate with the sides of the dice. So to start, we can gather rolls and sides from the user using input(). Next we can use the sides to generate our list that we pull from, you could use randint method in place of this, but for using choice we can make a list in range(1, sides+1). Next we can initiate a dictionary using dict and make a dictionary that has all the sides as keys with a value of 0. Now looks like this d = {1:0, 2:0...n+1:0}.From here now we can use a for loop to populate our dictionary adding 1 to whatever side is rolled. Another for loop will let us print out our dictionary. Bonus. I threw in a max function that takes the items in our dictionary and sorts them by their values and returns the largest tuple of (key, value). We can then print a most rolled statement.

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
vash_the_stampede
  • 4,590
  • 1
  • 8
  • 20
  • What if you didn’t want the user input and it was to be randomly generated for all of them? – Shakespeareeee Oct 09 '18 at 05:16
  • @Shakespeareeee You could just assign whatever you want to `rolls =` and `sides =` still will function the same – vash_the_stampede Oct 09 '18 at 05:18
  • I’m trying to make the output say “1: x amount of times rolled 2: x amount of times rolled” so on and so forth... I’ve been stuck on it for quite a while. I’m at a loss unfortunately. – Shakespeareeee Oct 09 '18 at 05:19