Home > database >  Adding the sum of the amount of numbers generated from a tuple
Adding the sum of the amount of numbers generated from a tuple

Time:10-29

Basically what I'm trying to get at is below my program will generate a shuffle between the numbers in the tuple below, for example if it generates [3,2,2,4,5,6] then the program would add up the values of 1 since there's no ones generated it would print as 0, then it would add up the values of 2 since there's 2 twos it would add up the value to 4 and print out a 4 etc etc.

from random import shuffle 

def make_roll() -> tuple:
    roll_number = [1,2,3,4,5,6]
    shuffle(roll_number)
    print(f'Rolling the dice...{roll_number}')

CodePudding user response:

The question is quite unclear, but assuming you first generate a random set of dice roll, then want to count the point per face value.

from random import choices
from collections import Counter

rolls = choices(range(1, 7), k=6)
# [3, 2, 2, 4, 5, 6]

c = Counter(rolls)
out = [c[i]*i for i in range(1, 7)]  # generic: range(1, max(c) 1)

# [0, 4, 3, 4, 5, 6]

CodePudding user response:

You could also use a Counter object.

Counter()

Code

from collections import Counter

lst = [4,3,3,2,2,2,1,1]
c = Counter()
for n in lst:        #creates a dictionary of occurences
  c[n]  = 1

for i in set(lst):   #select numbers and * by occurrences
  print(i * c[i])

Result

Counter({2: 3, 3: 2, 1: 2, 4: 1})

0
2
6
6
4

That way you could use something like c.total() to get the total number of rolls, or c.update() to update occurrences for a bonus roll e.g.

CodePudding user response:

numbers = [3,2,2,4,5,6]
for i in range(1,max(numbers) 1):
    n = 0
    for j in numbers:
        if i == j: n =j
    print(n)
  • Related