Contents
- ./file_handle.py
- ./linear_binary_search.py
- ./linear_search.py
- ./search_compare.py
- ./search_divide.py
- ./yearborn2.py
- ./yearborn.py
./file_handle.py 1/7
[top][prev][next]
# Demonstrate file handling exception
# Examples of errors:
# - file not found
# - don't have permission on the file
# Sara Sprenkle
import sys
def main():
if len(sys.argv) < 3:
print("Insufficient arguments")
print("Usage: python", sys.argv[0],"<infile> <outfile>")
sys.exit()
#infileName = input("What file do you want to read? ")
infileName = sys.argv[1]
# put the "correct"/"usual" behavior within the try
try:
inFile = open(infileName, "r")
# normally, we would do some sort of processing of the file here.
inFile.close()
except IOError as exc: # exc is the name of the raised exception
print("Error reading \"" + infileName + "\".")
# could be a variety of different problems, so print out
# the exception
print(exc)
print(type(exc)) # not helpful output for the user; just for demo purposes
sys.exit(1)
#outfileName = input("What file do you want to write? ")
outfileName = sys.argv[2]
try:
outFile = open(outfileName, "w")
# normally, we would do some sort of processing of the file here.
outFile.close()
except IOError as exc:
print("Error writing \"" + outfileName + "\".")
print(exc)
print(type(exc)) # not helpful output for the user; just for demo purposes
# no need to exit here because there is nothing else to do.
main()
./linear_binary_search.py 2/7
[top][prev][next]
# Demonstrate implementations of the linear and binary search
# techniques.
# Sara Sprenkle
# represents that binarySearch did not find the key
NOT_FOUND=-1
def main():
integers = range(1,20,2)
print("The list to search: ", integers)
print()
findMeList = [1, 4, 15, 16, 17]
for key in findMeList:
print("Search for", key)
print("Linear: Found?", linearSearch(integers, key))
# binarySearch returns the position the number was found, or -1 if it was
# not found. Translate the result from binarySearch to a True or False
pos = binarySearch(integers, key)
binFound = pos != NOT_FOUND
print("Binary: Found?", binFound)
print()
def linearSearch(searchlist, key):
"""
Returns the position of the key iff it is in the
list of integers searchlist.
"""
for pos in range(len(searchlist)):
if key == searchlist[pos]:
return pos
return NOT_FOUND
def binarySearch(searchlist, key):
""" Returns the position where key (an int) is found in the list of sorted
integers searchlist or -1 if key is not in the list. """
low = 0
high = len(searchlist)-1
while low <= high:
mid = (low+high)//2
valueAtMid = searchlist[mid]
if valueAtMid == key:
return mid
if valueAtMid < key: # search upper half
low = mid+1
else: # search lower half
high = mid-1
return NOT_FOUND
main()
./linear_search.py 3/7
[top][prev][next]
# Demonstrate implementation of the linear search technique.
# Sara Sprenkle
def main():
integers = range(1, 20, 2)
print("The list we are searching: ", integers)
print()
findMeList = [1, 4, 15, 16, 17]
for key in findMeList:
print("Search for", key)
print("Linear: Found?", linearSearch(integers, key))
print()
def linearSearch(searchlist, key):
for elem in searchlist:
if elem == key:
return True
return False
main()
./search_compare.py 4/7
[top][prev][next]
# Compare the linear and binary searching techniques by the number of
# comparisons.
# by Sara Sprenkle
def main():
print("This program helps us to empirically compare search strategies")
print()
# The keys I want to search for in a list
keys = [1, 4, 13, 19, 125, 126, 127, 19997, 19998, 19999]
NUM_ENTRIES = 10000
# the list of integers that I'm searching (odd numbers)
integers = list(range(1,NUM_ENTRIES*2,2))
print("Creating list of size", NUM_ENTRIES, "starting at 1 and incrementing by 2")
print()
print("%6s|%14s" % ("","# Comparisons"))
print("%6s| %6s %6s" % ("KEY", "LIN", "BIN"))
print("-"* 24)
total_lin_comp = 0.0
total_bin_comp = 0.0
for key in keys:
lin_comp = linearSearch(integers,key)
bin_comp = binarySearch(integers,key)
print("{:6d}| {:6d} {:6d}".format(key, lin_comp, bin_comp))
# update the total number of comparisons
total_lin_comp += lin_comp
total_bin_comp += bin_comp
print()
print("ON AVERAGE...")
print("-"*50)
print()
print("The average number of comparisons per search for")
print("\tlinear search was", total_lin_comp/len(keys))
print("\tbinary search was", total_bin_comp/len(keys))
print()
print("Disclaimer: May not be a completely fair comparison but gives us an idea.")
# Return the number of comparisons required to find the key.
def linearSearch(searchlist, key):
numChecks = 0
for elem in searchlist:
numChecks += 1
if elem == key:
return numChecks
return numChecks
# Return the number of comparisons required to find the key
def binarySearch(searchlist, key):
low = 0
high = len(searchlist)-1
numChecks = 0
while low <= high:
mid = (low+high)//2
numChecks+= 2 # while comparison, next if comparison
if searchlist[mid] == key:
return numChecks
numChecks+=1
if searchlist[mid] < key:
low = mid+1
else:
high = mid-1
return numChecks
main()
./search_divide.py 5/7
[top][prev][next]
# Binary search, dividing list in half
# Sara Sprenkle
# represents that binarySearch did not find the key
NOT_FOUND=-1
def main():
integers = range(1,20,2)
print("The list to search: ", integers)
print()
findMeList = [1, 4, 15, 16, 17]
for key in findMeList:
print("Search for", key)
# binarySearch returns the position the number was found, or -1 if it was
# not found. Translate the result from binarySearch to a True or False
pos = altBinarySearch(integers, key)
binFound = pos != NOT_FOUND
print("Binary: Found?", binFound)
print()
def altBinarySearch(searchlist, key):
"""Literally divide the list in half. Issues: creates multiple lists.
Each call to the function requires another list (of half the size of
the original)."""
# ran out of elements in the list
if len(searchlist) == 0:
return NOT_FOUND
low = 0
high = len(searchlist)-1
mid = (low+high)/2
valueAtMid = searchlist[mid]
if valueAtMid == key:
return mid
if low == high:
return NOT_FOUND
if searchlist[mid] < key: # search upper half
return altBinarySearch(searchlist[mid+1:], key)
else: # search lower half
return altBinarySearch(searchlist[:mid], key)
main()
./yearborn2.py 6/7
[top][prev][next]
# Demonstrate validating user input using a few techniques.
# Use if statements when possible.
# Excepts a certain error (ValueError); would not catch other
# exceptions in the except block.
# by CSCI111
import sys
def main():
print("This program determines your birth year")
print("given your age and the current year \n")
try:
age = int(input("Enter your age: "))
currentyear = int(input("Enter the current year: "))
except ValueError:
print("Error: Your input was not in the correct form.")
print("Enter integers for your age and the current year")
sys.exit(1)
if age < 0 or age > 115:
print("Come on: you have to be a reasonable age.")
elif currentyear < 0:
print("You need to have a positive year.")
else:
birthyear=currentyear - age
print("You were either born in", birthyear, "or", birthyear-1)
main()
./yearborn.py 7/7
[top][prev][next]
# Demonstrate validating user input using a few techniques
# Use if statements when possible.
# except statement will "catch" any exception.
# by CSCI111
import sys
def main():
print("This program determines your birth year")
print("given your age and the current year \n")
while True:
try:
age = int(input("Enter your age: "))
currentyear = int(input("Enter the current year: "))
break
except:
print("Error: Your input was not in the correct form.")
print("Enter integers for your age and the current year")
if age < 0 or age > 115:
print("Come on: you have to be a reasonable age.")
elif currentyear < 0:
print("You need to have a positive year.")
else:
birthyear=currentyear - age
print("You were either born in", birthyear, "or", birthyear-1)
main()
Generated by GNU Enscript 1.6.5.90.