Contents
- avgData.py
- daysOfWeek.py
- fibs2.py
- fibs.py
- file_search2.py
- file_search3.py
- file_search.py
- file_write.py
- wheeloffortune.py
- writeSumFile.py
avgData.py 1/10
[top][prev][next]
# Read in a file of temperatures and print out the average
# by CS111
#
inputfile = raw_input("Which file to average? ")
# opens the file in "read" mode
dataFile = file(inputfile, "r")
totalTemp=0
numTemps=0
# reads in the file and prints the content of the file
for line in dataFile:
# removing trailing and beginning whitespace
line = line.strip()
if line != "":
temp = float(line)
totalTemp += temp
numTemps += 1
dataFile.close()
# Compute the average
if numTemps != 0 :
avgTemp = float(totalTemp)/numTemps
print "The average temperature is %.2f" % avgTemp
else:
print "The file contained no temperatures."
daysOfWeek.py 2/10
[top][prev][next]
# Example illustrating list operations: concatenation and iteration
# by Sara Sprenkle
weekDays = ["Mon", "Tue", "Wed", "Thu", "Fri"]
weekendDays = ["Sat", "Sun"]
daysOfWeek = weekDays + weekendDays
print "The Days of the Week:"
for day in daysOfWeek:
print day
print "\nAGAIN!"
for x in xrange(len(daysOfWeek)):
print daysOfWeek[x]
fibs2.py 3/10
[top][prev][next]
# Example of creating a list of the appropriate size
# Computes the first SIZE Fibonacci numbers
# Sara Sprenkle
SIZE = 15
print "This program generates the first", SIZE, "Fibonacci numbers"
# creates a list of size 15, containing elements 0 to 14
fibs = range(SIZE)
fibs[0] = 1
fibs[1] = 1
for x in xrange(2,SIZE):
newfib = fibs[x-1]+fibs[x-2]
fibs[x] = newfib
#for num in fibs:
# print num
print fibs
fibs.py 4/10
[top][prev][next]
# Example of appending to a list
# Computes the first SIZE Fibonacci numbers
# Sara Sprenkle
SIZE = 15
print "This program generates the first", SIZE, "Fibonacci numbers"
# create an empty list
fibs = []
# append the first two Fibonacci numbers
fibs.append(1)
fibs.append(1)
# compute the next 13 Fibonacci numbers
for x in xrange(2,SIZE):
newfib = fibs[x-1]+fibs[x-2]
fibs.append(newfib)
# print the Fibonacci numbers as a list
print fibs
file_search2.py 5/10
[top][prev][next]
# Opens a file, reads the file one line at a time,
# searching for data from the user.
# Ignores lines that begin with "#" as comments.
# by CS111
# Make a constant so easy to change if what signifies a commented line
# changes.
COMMENT = "#"
inputfile = "data/years2.dat"
searchTerm = raw_input("What are you looking for? ")
# opens the file in "read" mode
dataFile = file(inputfile, "r")
# set up accumulators
lineNum = 0
numOccurrences = 0
# reads in the file and prints the content of the file
for line in dataFile:
lineNum+=1
# removes the trailing and beginning whitespace
line = line.strip()
# skip the commented lines
if not line.startswith(COMMENT):
# look for the line
if searchTerm in line:
print "Found %s in line %d: \"%s\"" % (searchTerm, lineNum, line)
numOccurrences+=1
# close the file with the method "close"
dataFile.close()
# Report findings ...
print searchTerm, "was found", numOccurrences, "times"
file_search3.py 6/10
[top][prev][next]
# Opens a file, reads the file one line at a time,
# searching for data from the user.
# Ignores anything after the '#' sign
# by CS111
# Make a constant so easy to change if what signifies a commented line
# changes.
COMMENT = "#"
inputfile = "data/years3.dat"
searchTerm = raw_input("What are you looking for? ")
# opens the file in "read" mode
dataFile = file(inputfile, "r")
# set up accumulators
lineNum = 0
numOccurrences = 0
# reads in the file and prints the content of the file
for line in dataFile:
lineNum+=1
# removes the trailing and beginning whitespace
line = line.strip()
# only do the find if we know that the comment is in the
# string
if COMMENT in line:
# the position of the comment in the string
commentPos = line.find(COMMENT)
# get only what's after the comment
line = line[:commentPos]
# look for the searchTerm in the line
if searchTerm in line:
print "Found %s in line %d: \"%s\"" % (searchTerm, lineNum, line)
numOccurrences+=1
# close the file with the method "close"
dataFile.close()
# Report findings ...
print searchTerm, "was found", numOccurrences, "times"
file_search.py 7/10
[top][prev][next]
# Opens a file, reads the file one line at a time,
# searching for data from the user
# by CS111
FILENAME="data/years.dat"
searchTerm = raw_input("What are you looking for? ")
# opens the file in "read" mode
dataFile = file(FILENAME, "r")
# Set up accumulators
lineNum=0
numOccurrences=0
# reads in the file and prints the content of the file
for line in dataFile:
lineNum+=1
# strip is a string method that
# removes the trailing and beginning whitespace
line = line.strip()
# look for the line
if searchTerm in line:
print "Found %s in line %d: \"%s\"" % (searchTerm, lineNum, line)
numOccurrences+=1
# close the file with the method "close"
dataFile.close()
# Report findings ...
print searchTerm, "was found", numOccurrences, "times"
file_write.py 8/10
[top][prev][next]
# Writes content from a user to a file
# by Sara Sprenkle
PROMPT = "What do you want to add to the file? (Nothing will exit): "
outfilename = raw_input("What is the name of your output file? ")
# opens the file in "write" mode
dataFile = file(outfilename, "w")
while True:
userinput = raw_input(PROMPT)
if userinput == "" :
break
# write the user's input to the file
dataFile.write(userinput)
# write a newline after each input from the user
dataFile.write("\n")
# Example of how to write numeric data to the file
#
# close the file with the method "close"
dataFile.close()
wheeloffortune.py 9/10
[top][prev][next]
# Wheel of Fortune
# - Updated to use a file of puzzles ...
# - Added functions to improve readability
# Sara Sprenkle
def main():
PUZZLE_FILENAME="data/puzzles.txt"
PROMPT="Enter a letter or try to solve the puzzle: "
TITLE_WIDTH=50
printHeader(TITLE_WIDTH)
print
print "Let's get started!"
puzzleFile = file(PUZZLE_FILENAME, "r")
puzzleid = 0
# each line in the puzzleFile is a puzzle
# go through them all ...
for puzzle in puzzleFile:
puzzle = puzzle.strip()
puzzleid+=1
# Display the current puzzle. All the characters (except for spaces)
# are displayed as underscores
displayedPuzzle = displayPuzzle(puzzle)
print "Puzzle %d: %s" % (puzzleid, displayedPuzzle)
# how many guesses it took the user to get it right
numGuesses = 1
guess = raw_input(PROMPT)
# Check if the user's guess matches the phrase
while guess.upper() != puzzle.upper() :
# handle a letter guess
if len(guess) == 1:
numOccurences = puzzle.count(guess) + puzzle.count(guess.swapcase())
if numOccurences > 0:
print "There are", numOccurences, guess + "'s", "in the phrase"
# fill in puzzle with guessed letter
displayedPuzzle = updateDisplayedPuzzle(displayedPuzzle, guess, puzzle)
print "\nThe puzzle is", displayedPuzzle
else:
print "Sorry, there are no", guess + "'s", "in the word"
# handle an incorrect guess of the phrase
else:
print "You guessed incorrectly."
print
guess = raw_input(PROMPT)
numGuesses += 1
print "Congratulations! You solved the puzzle in", numGuesses, "guesses"
puzzleFile.close()
# display a nice header for this program, with the given width
def printHeader(width):
# print out a nice header
print "*"*width
print "WHEEL".center(width)
print "OF".center(width)
print "FORTUNE!".center(width)
print "*"*width
# returns a string that represents the puzzle, replacing characters with
# underscores.
def displayPuzzle(puzzle):
displayedPuzzle = ""
for char in puzzle:
if char.isalpha():
displayedPuzzle += "_"
else:
displayedPuzzle += char
return displayedPuzzle
# Returns the updated puzzle to display, given the current displayed puzzle,
# the user's guess, and the puzzle
def updateDisplayedPuzzle(displayedPuzzle, guess, puzzle):
updatedpuzzle=""
for pos in xrange(len(puzzle)):
if puzzle[pos] == guess or puzzle[pos] == guess.swapcase():
updatedpuzzle += puzzle[pos]
else:
updatedpuzzle += displayedPuzzle[pos]
return updatedpuzzle
main()
writeSumFile.py 10/10
[top][prev][next]
# Create a file that summarizes how many students from each year are
# in the class.
# Not an efficient solution because reads through the file four times.
# We should revisit this problem later.
# by Sara Sprenkle
# Constants representing the different years
FRESHMAN = "FR"
SOPHOMORE = "SO"
JUNIOR = "JR"
SENIOR = "SR"
# Constant representing the special symbols of a comment
COMMENT = "#"
def main() :
infilename = raw_input("What class file do you want to search? ")
outfilename = raw_input("What is the name of your summary output file? ")
outFile = file(outfilename, "w")
outFile.write("# Summarized from file: " + infilename + "\n")
outFile.write("# Number of students from each year in the class\n")
fr_count = search_file(infilename, FRESHMAN)
so_count = search_file(infilename, SOPHOMORE)
jr_count = search_file(infilename, JUNIOR)
sr_count = search_file(infilename, SENIOR)
outFile.write("%s %d\n" % (FRESHMAN, fr_count) )
outFile.write("%s %d\n" % (SOPHOMORE, so_count) )
outFile.write("%s %d\n" % (JUNIOR, jr_count) )
outFile.write("%s %d\n" % (SENIOR, sr_count) )
outFile.close()
# input: the name of the file to search, the term to search for
# output: returns the number of occurences of the string searchFor in
# the file.
# Note: we can make this function more general by having an Boolean
# input parameter for ignoring comments
def search_file(filename, searchFor):
# opens the file in "read" mode
dataFile = file(filename, "r")
numOccurences = 0
# reads in the file and prints the content of the file
for line in dataFile:
# we can ignore comments or not with the last parameter
if search_line(line, searchFor, True):
numOccurences += 1
# close the file with the method "close"
dataFile.close()
return numOccurences
# input: the line to search, the term to search for,
# a boolean for if we should ignore comments or not
# output: returns True iff the string contains the string searchFor
def search_line(line, searchFor, ignoreComments):
# removes the trailing and beginning whitespace
line = line.strip()
if ignoreComments:
# only do the find if we know that the comment is in the
# string
if COMMENT in line:
# the position of the comment in the string
commentPos = line.find(COMMENT)
# get only what's after the comment
line = line[:commentPos]
if searchFor in line:
# no side effects: don't print
# print "I found", searchFor, "in line \""+ line + "\""
return True
return False
main()
Generated by GNU enscript 1.6.4.