Contents

  1. ./avgData.py
  2. ./demoWrite.py
  3. ./descendSort.py
  4. ./file_read.py
  5. ./file_write.py
  6. ./for_file_read.py
  7. ./reportAvgData.py
  8. ./using_readline_getridofnewline.py
  9. ./using_readline.py
  10. ./wheeloffortune.py
  11. ./wheeloffortune_wfiles.py

./avgData.py 1/11

[
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/alaska.dat"

LOCATIONS=["Alaska", "Florida", "Virginia"]
DATA_DIR="data"
DATA_EXT = ".dat"

def main():
    
    # Simpler version: 
    print("Processing", DATAFILE)
    avgTemp = calculateAvgTemp(DATAFILE)
    print("The average temperature is {:.2f}".format(avgTemp))
    
    # get the average temperature for a bunch of files
    print("\nProcess a bunch of files:")
    for location in LOCATIONS:
        filename = DATA_DIR + "/" + location.lower() + DATA_EXT
        avgTemp = calculateAvgTemp(filename)
    
        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
    """
    tempFile = open(datafileName, "r")
    
    totalTemp = 0
    numTemps = 0
    for tempLine in tempFile: 
        totalTemp += float(tempLine)
        numTemps = numTemps + 1
    
    # close the file because we opened it
    tempFile.close()
    
    avgTemp = totalTemp/numTemps
    return avgTemp
        

main()













./demoWrite.py 2/11

[
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("Also this")

myFile.close()

./descendSort.py 3/11

[
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 4/11

[
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, end="")



./file_write.py 5/11

[
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()

./for_file_read.py 6/11

[
top][prev][next]
# Opens a file, reads the file one line at a time, and prints the
# contents
# by Sara Sprenkle

FILENAME="data/famous_pairs.txt"

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

# reads in the file line-by-line and prints the content of the file
for line in dataFile:
    line = line.rstrip("\n")
    print(line)
    

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

./reportAvgData.py 7/11

[
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():
    summaryReport = open(DATA_DIR + "/" + SUMMARY_FILE_NAME, "w")
    for location in LOCATIONS:
        filename = DATA_DIR + "/" + location.lower() + DATA_EXT
        avgTemp = calculateAvgTemp(filename)
        summaryReport.write("{:s} {:.2f}\n".format(location, avgTemp))
        print("The average temperature in {:s} is {:.2f}".format(location, avgTemp))
    summaryReport.close()

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
    """
    tempFile = open(datafileName, "r")
    
    totalTemp = 0
    numTemps = 0
    for tempLine in tempFile: 
        totalTemp += float(tempLine)
        numTemps = numTemps + 1
    
    # close the file because we opened it
    tempFile.close()

    avgTemp = totalTemp/numTemps
    return avgTemp


main()

./using_readline_getridofnewline.py 8/11

[
top][prev][next]
# One way to use readline()
# by Sara Sprenkle

FILENAME="data/famous_pairs.txt"

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

# reads in the file line-by-line and prints the content of the file
line = dataFile.readline()

while line != "":
    # the line always has a newline character at the end.
    # we could print without adding the newline from the print.
    print(line, end="") # just to do something with that line.
    
    # or we could modify the string so that it doesn't contain
    # the newline character, e.g., (two ways): 
    lineWithoutNewLine = line[:-1] # we want all but the last character ("\n")
    lineWithoutNewLine2 = line.strip("\n") # removes the \n from the string
    
    # now, do something with the line without the new line character...
    print(lineWithoutNewLine)
    
    line = dataFile.readline()
    
# What happens when we try to read the next line, after we have already
# read through the file?
line = dataFile.readline()
# Answer: That line is also an empty string:
print(line)

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

./using_readline.py 9/11

[
top][prev][next]
# One way to use readline()
# Note that the output doesn't quite match the original file.
#    Why not?  (How is it different and what is the cause of 
#    the difference?)
#    How can you fix that?
# by Sara Sprenkle

FILENAME="data/famous_pairs.txt"

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

# reads in the file line-by-line and prints the content of the file
line = dataFile.readline()

while line != "":
    print(line) # just to do something with that line.
    
    line = dataFile.readline()
    
# What happens when we try to read the next line, after we have already
# read through the file?
line = dataFile.readline()
# Answer: That line is also an empty string:
print(line)

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

./wheeloffortune.py 10/11

[
top][prev][next]
# Wheel of Fortune
# the puzzle is hardcoded, so there is only one :(
# By Sara Sprenkle

PUZZLE="Computational Thinkers".upper()
# PHRASE = ""
PROMPT="Enter a letter or try to solve the puzzle: "
TITLE_WIDTH=50

def main():
    
    displayHeader()
    
    # Display the current puzzle.  
    displayedPuzzle = createDisplayedPuzzle(PUZZLE)
    
    print ("The puzzle:", displayedPuzzle)
    
    print()
    
    # 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")
                    
                    displayedPuzzle=fillLetterInDisplayedPuzzle(guess, PUZZLE, displayedPuzzle)
                    
                    print ("\n\t", displayedPuzzle)
                else:
                    print ("Sorry, there are no", guess + "'s", "in the word")
                    
                lettersLeft.remove(guess.lower())
                
            if numGuesses % 3 == 0: 
                print("\nRemaining letters: ")
                for letter in lettersLeft:
                    print(letter,end=" ")
                print()
        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.")
        
        print()
        guess = input(PROMPT)
        numGuesses += 1
            
    print ("Congratulations!  You solved the puzzle in", numGuesses, "guesses")

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()

./wheeloffortune_wfiles.py 11/11

[
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.5.90.