Python homework

Python python at bladeshadow.org
Mon Dec 11 15:53:25 EST 2017


On Tue, Dec 05, 2017 at 09:02:54PM +1200, ssghotra1997 wrote:
>     for i in range(num):
>         rolls = int(random.randint(1, 6))
>         if rolls == 1:
>             sides['One'] += 1
[...]

Using integers as the key makes the code a bit shorter...  That
approach is also better if you're using a function where you don't
know the full range, or if the range is very large.  In that case, you
don't need to initialize the dictionary; you can instead test if the
index exists in the dictionary already, and if not set its value to 1.
Much harder to do that if you use text keys (but not impossible--you
could write a function that converts numbers to their text names).

This is Python 2.7, but there's very little difference from the 3.x
version:

-=-=-=-=-=-=-=-
#!/usr/bin/python
import random
def roll_die(times):
    sides = {1:0, 2:0, 3:0, 4:0, 5:0, 6:0}
    for i in range(times):
        roll = int(random.randint(1, 6))
        sides[roll] += 1
    return sides, max(sides,key=sides.get)

(rolls, max_side) = roll_die(50)
print rolls
print "%d was rolled the most: %d times." % (max_side, rolls[max_side]) 
-=-=-=-=-=-=-=-


Both versions have a flaw:  If there is a tie, only one is printed:

$ ./sides.py
{1: 11, 2: 7, 3: 6, 4: 6, 5: 11, 6: 9}
1 was rolled the most: 11 times.

[So was 5.]

Here's a version that prints all sides that were rolled the maximum
number of times:

-=-=-=-=-=-=-=-
#!/usr/bin/python
import random

def roll_die(times):
    sides = {1:0, 2:0, 3:0, 4:0, 5:0, 6:0}
    max_rolls_sides = []

    # roll the dice...
    for i in range(times):
        roll = int(random.randint(1, 6))
        sides[roll] += 1

    # find the first side which was rolled the maximum number
    index = max(sides, key=sides.get)

    # get the number of rolls for the side we just got
    max_rolls = sides[index]

    # now find all sides that have that number of rolls
    for i in range(6):
        current_side = i + 1
        if sides[current_side] == max_rolls:
            max_rolls_sides.append(current_side)
    
    # return all those things in a tuple
    return sides, max_rolls, max_rolls_sides

# roll the dice 50 times, and print the results
(rolls, max_roll, max_roll_sides) = roll_die(50)
print rolls
print "max rolls of %d was rolled on sides: %s." % (max_roll, max_roll_sides)
-=-=-=-=-=-=-=-

[The lines to calculate the index and the max_rolls can be combined,
but I left them explicitly separated as I felt it improved clarity.]

$ ./sides.py
{1: 11, 2: 11, 3: 7, 4: 6, 5: 9, 6: 6}
max rolls of 11 was rolled on sides: [1, 2].

$ ./sides.py
{1: 8, 2: 9, 3: 9, 4: 7, 5: 8, 6: 9}
max rolls of 9 was rolled on sides: [2, 3, 6].




More information about the Python-list mailing list