Contents
- avgData.py
- avgDataWithWhile.py
- file_read.py
- file_write.py
- for_file_read.py
- reportAvgData.py
- using_readline.py
- wheeloffortune.py
- wheeloffortune.wfiles.py
- wof_snippets.py
avgData.py 1/10
[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 for loop to read the file
# 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
for line in dataFile:
# 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
# close the file
dataFile.close()
# calculate the average
average = tempSum/numTemps
# return the average
return average
main()
avgDataWithWhile.py 2/10
[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()
file_read.py 3/10
[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_write.py 4/10
[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/"
outfilename = input("What is the name of your output file (in data/ directory)? ")
numLines = eval(input("How many lines do you want to write? "))
# create a new file object, in "write" mode
dataFile = open(DATA_DIR + outfilename, "w")
for x in range(numLines):
userinput = input(PROMPT)
# write the user's input to the file
dataFile.write(userinput)
# write a newline after each input from the user
dataFile.write("\n")
# close the file with the method "close"
dataFile.close()
for_file_read.py 5/10
[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.strip("\n")
print(line)
# close the file with the method "close"
dataFile.close()
reportAvgData.py 6/10
[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()
using_readline.py 7/10
[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 != "":
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 8/10
[top][prev][next]
# Wheel of Fortune
# the puzzle is hardcoded, so there is only one puzzle :(
# 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())
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")
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 9/10
[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()
wof_snippets.py 10/10
[top][prev][next]
##########################################################################
# Wheel of Fortune Snippets
# Not complete code, just trying to sketch out solutions to subproblems
##########################################################################
categories = ["whatareyoudoing", "beforeandafter", "famous_pairs"]
# Alternative 1: Display the categories
for i in range(len(categories)):
print("Press", i+1, "for", categories[i])
# Alternative 2: Display the categories
i=1
for category in categories:
print("Press", i, "for", category)
catNum = int(input("Which category do you choose?"))
if catNum < 1 or catNum > len(categories):
print("Error! Out of range!")
# exit
puzzleFileName = categories[catNum-1] + ".txt"
puzzleFile = open(puzzleFileName, "r")
# Alternative 1: Read the puzzles in the file
for line in puzzleFile:
puzzle = line.strip()
# Alternative 2: Read the puzzles in the file
line = puzzleFile.readline()
while line != "":
puzzle = line.strip()
# process the puzzle
Generated by GNU Enscript 1.6.6.