Contents

  1. dictionary_helpers.py
  2. game.py
  3. majors_dictionary.py

dictionary_helpers.py 1/3

[
top][prev][next]
# Dictionary Helpers ...

# Display the dictionary, with the keys in sorted order
# Input: the dictionary to display
def displaySortedDictionary( dictionary ):
    keys = dictionary.keys()
    keys.sort()

    for key in keys:
        print key, "-->", 
        print dictionary[key]

# Update the dictionary
# Precondition: dictionary that maps keys to a count;
# a key that may or may not already be in the dictionary
def updateDictionary( dictionary, key = "undeclared" ):
    # add to the dictionary (count is 1)
    if key not in dictionary : 
        dictionary[key] = 1
    else: 
        value = dictionary[key] + 1
        dictionary[key] = value

game.py 2/3

[
top][prev][next]
# Game Module
# Contains useful functions and modules for various games
# by Sara Sprenkle

import random

# constants for flipping a coin
HEADS = 0
TAILS = 1

def testMe():
    print rollDie(6)
    print rollDie()
    print rollDie(12)
    print rollDie()

# No pre- or post- condition
# return HEADS or TAILS, randomly
def coinFlip():
    return random.randint(0,1)


def rollDie(sides=6):
    """ input: the number of sides of the die (defaults to 6)
 return a random number between 1 and sides, inclusive """
    print "Num sides =", sides
    return random.randint(1,sides)
    
# input: the number of dice to roll and the number of sides of
# the dice (defaults to 6).
# return the total of rolling all the dice
def rollMultipleDice(numDice, sides=6):
    total = 0
    for x in xrange(numDice):
        total += rollDie(sides)
    return roll


# Remove this line after done testing.
# Otherwise, will call the testMe function when game module is
# imported.
testMe()

majors_dictionary.py 3/3

[
top][prev][next]
# Determine the number of students in each major
# Assumes the file contains
# <LASTNAME> [<MAJORS>]
# by CS111

MAJORSFILE = "data/majors.all.dat"

from dictionary_helpers import *

# open the majors file
majorsFile = file(MAJORSFILE, "r")

# create the dictionary that maps majors --> number of majors
majorsToNumStudents = {}

for line in majorsFile:
    # a line of the file contains a student's last name and then their list of majors  
    
    # split the line into "words"
    dataList = line.split()

    # the first word is the student's last name
    lastName = dataList[0]
    
    # check if the student has a major
    if len(dataList) > 1:
        # the rest of dataList is a list of majors
        majorsList = dataList[1:]
        
        # update the dictionary for every major
        for major in majorsList:
            updateDictionary(majorsToNumStudents, major)
    else:
        # student doesn't have a major
        updateDictionary(majorsToNumStudents)

majorsFile.close()

displaySortedDictionary( majorsToNumStudents)

Generated by GNU enscript 1.6.4.