Contents
- descendSort.py
- file_read.py
- for_file_read.py
- swap.py
- wheeloffortune.py
- wheeloffortune.wfiles.py
descendSort.py 1/6
[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 2/6
[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)
for_file_read.py 3/6
[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()
swap.py 4/6
[top][prev][next]
# Review: Attempt at swapping two variables in a function
# FAIL! Swapping within a function won't work. :(
# Why? With immutable data types (like integers), the functions are
# passed *copies* of the parameters, not the original variables
def main():
x = 5
y = 7
print("In main:")
print("x =", x)
print("y =", y)
swap(x, y)
print("In main after call to swap:")
print("x =", x)
print("y =", y)
def swap(a, b):
"""
Swaps the values stored in a and b
"""
tmp = a
a = b
b = tmp
print("In swap function: ", a, b)
main()
wheeloffortune.py 5/6
[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())
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.")
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 6/6
[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.