Python-list Digest, Vol 171, Issue 7

ROGER GRAYDON CHRISTMAN dvl at psu.edu
Wed Dec 6 10:15:09 EST 2017


On Wed, Dec  6, 2017, ssghotra1997 wrote:
import random

def rollDie(num):
    sides = {'One':0, 'Two':0,'Three':0,'Four':0,'Five':0,'Six':0}

    for i in range(num):
        rolls = int(random.randint(1, 6)
        if rolls == 1:
            sides['One'] += 1
        if rolls == 2:
            sides['Two'] += 1
        if rolls == 3:
            sides['Three'] += 1
        if rolls == 4:
            sides['Four'] += 1
        if rolls == 5:
            sides['Five'] += 1
        if rolls == 6:
            sides['Six'] += 1

    return sides,max(sides,key=sides.get)

print(rollDie(50)


*********************** OUTPUT *********************************************
({'One': 10, 'Two': 7, 'Three': 7, 'Four': 11, 'Five': 7, 'Six': 8}, 'Four')

You should always be suspicious if any case where you see identical
or nearly-identical code duplicated more than three times, because that
strongly suggests that there is a much better way that avoids such 
code duplication.

This problem of identifying a most frequent die roll could be applicable
to imaginary dice of any size, since the concept would e the same.
Imagine how much tedious work you would have to do if the question
was about a 20-sided die or a 34-sided die!

Of course, there is the special feature here of using words ('One', 'Two'..)
to stand for the numbers, but even those could be addressed very neatly
with a hand data structure and no code complexity.

It might not make much difference for a homework assignment of this
size at this point in your curriculum.  But later on, you would pay a heavy
price for choosing implementations that require 5, 10, or 20 times as much
code as necessary.   The increase in program size would have a multiplicative
effect on writing time and debugging time and would have an adverse affect
on a course grade, product delivery date, customer satisfaction, and
job security.

So learn how to find the efficient solutions now while you still have
instructors around to help you.

Roger Christman
Pennsylvania State University





More information about the Python-list mailing list