Contents

  1. avgData.py
  2. avgDataWithWhile.py
  3. demoWrite.py
  4. descendSort.py
  5. file_read.py
  6. file_search.py
  7. file_write.py
  8. reportAvgData.py
  9. wheeloffortune.wfiles.py

avgData.py 1/9

[
top][prev][next]
# Computes the average high temperature from a file that contains the daily
# high temperatures for last year at one location.
# By CSCI111

DATAFILE="data/florida.dat"


def main():
    
    # can change this later to get user input for the filename or 
    # loop through a bunch of file names or ...
    avgTemp = calculateAvgTemp(DATAFILE)
    
    print("The average temperature is {:.2f}".format(avgTemp))


def calculateAvgTemp( datafileName ):
    """
    Given the name of the data file formatted such that there is a 
    temperature on each line of the file, calculates and returns 
    the average of all the temperatures in the file as a float
    """
    dataFile = open(datafileName, "r")
    
    # accumulator to add the temperature to a total temperature
    totalTemp = 0
    # accumulator to add up the total number of lines
    tempCount = 0
    
    # go through each line in the file
    for line in dataFile:
        # on each line convert line --> float
        # no need to remove the last \n from the line
        temperature=float(line)
        
        # add the temperature to the accumulator
        totalTemp += temperature
        # update the number of temperatures read in
        tempCount += 1
        
    dataFile.close()
    
    # calculate the average
    average = totalTemp/tempCount
    return average
        

main()

avgDataWithWhile.py 2/9

[
top][prev][next]
# Computes the average high temperature from a file that contains the daily
# high temperatures for last year at one location.
# Implemented using a while loop to read the file
# Notice how little has changed between this version and the avgData.py version
# By CSCI111

DATAFILE="data/florida.dat"


def main():
    
    # can change this later to get user input for the filename or 
    # loop through a bunch of file names or ...
    avgTemp = calculateAvgTemp(DATAFILE)
    
    print("The average temperature is {:.2f}".format(avgTemp))


def calculateAvgTemp( datafileName ):
    """
    Given the name of the data file formatted such that there is a 
    temperature on each line of the file, calculates and returns 
    the average of all the temperatures in the file as a float
    """
    # open the file
    dataFile = open( datafileName, "r")
    
    tempSum = 0
    numTemps = 0
    
    # read the file, line by line
    line = dataFile.readline()
    
    while line != "":
        # convert the line to a float --> temperature
        temperature = float(line)
    
        # accumulate the temperatures
        tempSum = tempSum + temperature
    
        # accumulate the number of lines in the file
        numTemps += 1
    
        line = dataFile.readline()
    
    # close the file
    dataFile.close()
    
    # calculate the average
    average = tempSum/numTemps
   
    # return the average
    return average



main()

demoWrite.py 3/9

[
top][prev][next]
# Write strings to a file
# By Sara Sprenkle

myFile = open("data/demo.txt", "w")


myFile.write("Write string to file")
myFile.write("\n")
myFile.write("Also this")

myFile.close()

descendSort.py 4/9

[
top][prev][next]
# Demonstrate passing lists to functions
# One function modifies the list parameter, 
# one function is a "pure function" and does not modify the parameter
# CSCI111

import test

def main():
    # test descendSort3Nums
    aList = [1,2,3]
    descendSort3Nums(aList)
    print(aList)

    aList = [0, 5, -3]
    descendSort3Nums(aList)
    print(aList)
    
    aList = [7,4,1]
    descendSort3Nums(aList)
    print(aList)
    
    aList = [-1, -1, -3]
    descendSort3Nums(aList)
    print(aList)
    
    aList = [-1, -5, -3]
    descendSort3Nums(aList)
    print(aList)

def descendSort3Nums(list3):
    """
    Parameter: list3: a list containing three numbers
    Sorts the list in descending order
    Note: does not return anything, no output 
    """
    if list3[1] > list3[0]:
        # swap 'em
        tmp = list3[0]
        list3[0] = list3[1]
        list3[1] = tmp

    if list3[2] > list3[1]:
        # swap 'em
        tmp = list3[1]
        list3[1] = list3[2]
        list3[2] = tmp
    
    if list3[1] > list3[0]:
        # swap 'em
        tmp = list3[0]
        list3[0] = list3[1]
        list3[1] = tmp

def createDescendingList(list3):
    """
    Parameter: list3: a list containing three numbers
    Sorts the list in descending order and returns that list
    (Example of "pure function")
    """
    copyOfList3 = list3 + []
    
    if copyOfList3[1] > copyOfList3[0]:
        # swap 'em
        tmp = copyOfList3[0]
        copyOfList3[0] = copyOfList3[1]
        copyOfList3[1] = tmp

    if copyOfList3[2] > copyOfList3[1]:
        # swap 'em
        tmp = copyOfList3[1]
        copyOfList3[1] = copyOfList3[2]
        copyOfList3[2] = tmp
    
    if copyOfList3[1] > copyOfList3[0]:
        # swap 'em
        tmp = copyOfList3[0]
        copyOfList3[0] = copyOfList3[1]
        copyOfList3[1] = tmp
        
    return copyOfList3

def testDescendSort3Nums():
    origList = [1, 2, 3]
    descendSort3Nums(origList)
    # test that the list sorted is in the other order
    test.testEqual( origList, [3, 2, 1])
    
    aList = [-1, -5, -3]
    descendSort3Nums(aList)
    test.testEqual( aList, [-1, -3, -5])

def testCreateDescendingSort3Nums():
    origList = [1, 2, 3]
    test.testEqual( createDescendingList(origList), [3, 2, 1])
    # verify that the original list didn't change.
    test.testEqual( origList, [1, 2, 3] )
    
    aList = [-1, -5, -3]
    test.testEqual( createDescendingList(aList), [-1, -3, -5])
    test.testEqual( aList, [-1, -5, -3])

testDescendSort3Nums()
testCreateDescendingSort3Nums()

#main()

file_read.py 5/9

[
top][prev][next]
# Opens a file, reads it, and prints out its contents.
# by Sara Sprenkle

FILENAME="data/famous_pairs.txt"

# creates a new file object, opening the file in read mode
myFile = open(FILENAME, "r")

# read the file and put it into one string
contents = myFile.read()

# close the file when you're done reading the file
myFile.close()

# display the contents of the file
print(contents)

file_search.py 6/9

[
top][prev][next]
# Given a file and a term to search for,
# find which lines the term is on and the
# total number of lines that contained that term
# By CSCI 111

FILENAME="data/wikipedia.txt"

print("This program will find out how many lines the given search term")
print("is on in", FILENAME,"and show those lines")
print()
print("Looking at file", FILENAME)
print()

searchFor = "dog" # later, get user input
#searchFor = input("What term do you want to search for? ")


myFile = open(FILENAME, "r")

lineNum = 0
termCount = 0

# look through the file line by line
for line in myFile:
    lineNum += 1
    line = line[:-1]
    # on each line, check if it contains the term we're searching for
    if searchFor in line:
        print(lineNum, line)
        termCount += 1
        # if it does, print the line and the line number; 
        # update the count for the number of lines it's on

print("for a total of", termCount, "lines")
# close the file
myFile.close()

file_write.py 7/9

[
top][prev][next]
# Writes content from a user to a file
# by Sara Sprenkle

PROMPT = "Enter the next line in the file: "
DATA_DIR = "data/"

print("This program will write user-provided data to a user-defined filename.\n")

outfilename = input("What is the name of your output file (in data/ directory)? ")

print("\nThe program will exit when you press <Enter>\n")

# create a new file object, in "write" mode
dataFile = open(DATA_DIR + outfilename, "w")

userinput = input(PROMPT)

while userinput != "":
    # write the user's input to the file
    dataFile.write(userinput)
    # write a newline after each input from the user
    dataFile.write("\n")
    userinput = input(PROMPT)


# close the file with the method "close"
dataFile.close()

reportAvgData.py 8/9

[
top][prev][next]
# Computes the average high temperature from multiple locations.
# Each location has an associated file that contains the daily
# high temperatures for last year at one location.
# Writes a report about the data in the form:
# <locationname> <avgtemp>
# <locationname> <avgtemp>
# ...
#
# Average temperature should be displayed to two decimal places
# By CSCI111

DATA_DIR = "data/"
LOCATIONS = ["alaska", "florida", "virginia"]
DATA_EXT = ".dat"
SUMMARY_FILE_NAME = "all_locations.dat"

def main():
    
    for location in LOCATIONS:
        dataFileName = DATA_DIR + location + DATA_EXT
        avgTemp = calculateAvgTemp(dataFileName)
        print("The average temperature in {:s} is {:.2f}".format(location, avgTemp))


def calculateAvgTemp( datafileName ):
    """
    Given the name of the data file formatted such that there is a 
    temperature on each line of the file, calculates and returns 
    the average of all the temperatures in the file as a float
    """




main()

wheeloffortune.wfiles.py 9/9

[
top][prev][next]
# Wheel of Fortune
# -- but, probably more like hangman
# gets the puzzles from a file
# By Sara Sprenkle

PROMPT="Enter a letter or try to solve the puzzle: "
TITLE_WIDTH=50
PUZZLE_DIR = "data/"

def main():

    # print out a nice header
    displayHeader()

    categoryNames = ["whatareyoudoing", "beforeandafter", "famous_pairs"]

    for num in range(len(categoryNames)):
        print("Press", (num+1), "for", categoryNames[num])
    
    # input from user about which puzzle file to use
    selection = eval(input("Which category do you choose? "))
    
    # change categoryName to file names
    puzzleFile = open(PUZZLE_DIR + categoryNames[selection-1] + ".txt", "r")

    puzzleid = 1

    # each line in the puzzleFile is a puzzle
    # go through them all ...
    for puzzle in puzzleFile: 
        puzzle = puzzle.strip()
        puzzle = puzzle.upper()
    
        # Display the current puzzle.  
        displayedPuzzle = createDisplayedPuzzle(puzzle)

        print("\nPuzzle {:d}: {:s}\n".format(puzzleid, displayedPuzzle))
    
        # the number of guesses it takes to solve the puzzle
        numGuesses = 1
    
        guess = input(PROMPT)
        
        lettersLeft = generateLettersList()
    
        while guess.lower() != puzzle.lower() :
            if len(guess) == 1 and guess.isalpha(): 
                if guess not in lettersLeft and guess.swapcase() not in lettersLeft:
                    print("Sorry,", guess, "was already guessed!")
                else: 
                    numOccurences = puzzle.count(guess) + puzzle.count(guess.swapcase())
                    if numOccurences > 0:
                        print ("There are", numOccurences, guess + "'s", "in the phrase")
                        # fill in puzzle
                        displayedPuzzle=fillLetterInDisplayedPuzzle(guess, puzzle, displayedPuzzle)
                    
                        print ("\n\t", displayedPuzzle)
                    else:
                        print ("Sorry, there are no", guess + "'s", "in the word")
                    lettersLeft.remove(guess.lower())
                
            elif len(guess) != 1:
                # assumes that the user tried to solve the puzzle but got it wrong.
                print ("\tSorry, that is not correct.")
            else:
                print ("\tError: You must guess a letter.")
        
            if numGuesses % 3 == 0: 
                print("\nRemaining letters: ")
                for letter in lettersLeft:
                    print(letter,end=" ")
                print()
        
            print()
            guess = input(PROMPT)
            numGuesses += 1
            
            
            
        print ("Congratulations!  You solved the puzzle in", numGuesses, "guesses")
        puzzleid+=1
        
    puzzleFile.close()

    print("We're out of puzzles!  Thanks for playing!")

def displayHeader():
    """
    Display a beautiful header
    """
    print("*"*TITLE_WIDTH)
    print("WHEEL".center(TITLE_WIDTH))
    print("OF".center(TITLE_WIDTH))
    print("FORTUNE!".center(TITLE_WIDTH))
    print("*"*TITLE_WIDTH )
    
def createDisplayedPuzzle(puzzle):
    """
    Creates and returns the displayable puzzle from the puzzle
    All the alphabetical characters are displayed/represented as underscores.
    Parameter:
       puzzle - a string
    """
    displayedPuzzle = ""
    for char in puzzle:
        if char.isalpha():
            displayedPuzzle += "_"
        else:
            displayedPuzzle += char
    return displayedPuzzle


def fillLetterInDisplayedPuzzle(letter, puzzle, displayedPuzzle):
    """
    Replaces the blanks in the displayedPuzzle with the given letter and returns the 
    updated puzzle
    Parameters:
     - letter: the letter guessed (a single-character string)
     - puzzle: the puzzle, as a string
     - displayedPuzzle: the puzzle, as a string, but with _ for the unguessed letters
    Returns the updated puzzle to display
    """
    updatedPuzzle = ""
    for pos in range(len(puzzle)):
        if puzzle[pos] == letter or puzzle[pos] == letter.swapcase():
            updatedPuzzle += puzzle[pos]
        else:
            updatedPuzzle += displayedPuzzle[pos]
    return updatedPuzzle
    
def generateLettersList():
    letters = []
    for ascii in range( ord('a'), ord('z')+1 ):
        letters.append( chr(ascii) )
    return letters

main()

Generated by GNU Enscript 1.6.6.