Python homework

Mario R. Osorio nimbiotics at gmail.com
Thu Dec 7 08:19:37 EST 2017




On Tuesday, December 5, 2017 at 8:33:52 PM UTC-5, nick martinez wrote:
> I have a question on my homework. My homework is to write a program in which the computer simulates the rolling of a die 50
> times and then prints
> (i). the most frequent side of the die
> (ii). the average die value of all rolls. 
> I wrote the program so it says the most frequent number out of all the rolls for example (12,4,6,14,10,4) and will print out "14" instead of 4 like I need.
> This is what I have so far:
> import random
> 
> def rollDie(number):
>     rolls = [0] * 6
>     for i in range(0, number):
>         roll=int(random.randint(1,6))
>         rolls[roll - 1] += 1
>     return rolls
> 
> if __name__ == "__main__":
>     result = rollDie(50)
>     print (result)
>     print(max(result))

Just my 2 cents:

import random

def rollDie(number):
    rolls = {1:0, 2:0, 3:0, 4:0, 5:0, 6:0}
    for i in range(0, number):
        roll=int(random.randint(1,6))
        rolls[roll] += 1
    return rolls

if __name__ == "__main__":
    rolls = rollDie(50)
    most_rolled = rolls[max(rolls, key=lambda i: rolls[i])]
    top_rollers = [k for k,v in rolls.items() if v == most_rolled]
    print('The dice rolled: %s' % (rolls,))
    if len(top_rollers) > 1:
        message = 'The sides with most hits are %s, with %i hits each.'
    else:
        message = 'The side with most hits is %s, with %i hits'
    print(message % (top_rollers, most_rolled))

# Sample output:
# The dice rolled: {1: 10, 2: 10, 3: 7, 4: 7, 5: 10, 6: 6}
# The sides with most hits are [1, 2, 5], with 10 hits each.
#
# The dice rolled: {1: 7, 2: 11, 3: 10, 4: 6, 5: 8, 6: 8}
# The side with most hits is [2], with 11 hits




More information about the Python-list mailing list