s2whelan
s2whelan

Reputation: 11

How can I display something like "5 was rolled the most often (25 times)" at the bottom of this code?

As the question says, I need to display the most common dice roll and its frequency. It's a simulation and analysis question for school. I need the last line printed to read something like "x was rolled the most often (y times)"

from random import randint

print("Dice simulation and analysis program")
results = []
frequencies = [0, 0, 0, 0, 0, 0]

# Loop 100 times
for i in range (100):
    throw_result = randint(1,6) # store a random value between 1 and 6
    results.append(throw_result) # append each value to results

    # Start to build up a list of frequencies for each value thrown
    if throw_result == 1:
        frequencies[0] = frequencies[0] + 1
    elif throw_result == 2:
        frequencies[1] = frequencies[1] + 1
    elif throw_result == 3:
        frequencies[2] = frequencies[2] + 1
    elif throw_result == 4:
        frequencies[3] = frequencies[3] + 1
    elif throw_result == 5:
        frequencies[4] = frequencies[4] + 1
    elif throw_result == 6:
        frequencies[5] = frequencies[5] + 1

print()
# print("Results:", results)
print("Frequences:", frequencies)

print("Dice Frequency")
print("---- ---------")
print("1    ", frequencies[0])
print("2    ", frequencies[1])
print("3    ", frequencies[2])
print("4    ", frequencies[3])
print("5    ", frequencies[4])
print("6    ", frequencies[5])

Upvotes: 0

Views: 57

Answers (3)

Red Rapious
Red Rapious

Reputation: 61

You should really use

frequencies[i] += 1

instead of creating 6 different if/else statements. And to print the final frequencies, use a for loop:

for i in range(6):
   print(str(i + 1) + "    ", frequencies[i])

Upvotes: 0

nxht
nxht

Reputation: 477

max_ix = max(range(len(frequencies)), key= lambda x: frequencies[x])
print(f"{max_ix+1} was rolled the most often ({frequencies[max_ix]} times)")

Or easier way, you can use numpy.argmax

Upvotes: 0

Josh Clark
Josh Clark

Reputation: 1012

max will give you the highest value in an iterable. We can use index() on the frequencies array to find the index of the highest element. These two together give you the information you need to print your statement.

most_rolls = max(frequencies)
print(f"{frequencies.index(most_rolls) + 1} was rolled the most often ({most_rolls} times)")

Upvotes: 1

Related Questions