Contents
- binarysearch.py
- card.py
- linear_and_binary_search.py
- linear_search.py
- our_search.py
- search_compare.py
- search_divide.py
binarysearch.py 1/7
[top][prev][next]
def binarySearch(searchlist, key):
"""
Pre: searchlist is a list of integers in sorted order.
Returns the position of key (an integer) in the list of
integers (searchlist) or -1 if not found"""
low = 0 # lowest possible position
high = len(searchlist) - 1 # highest possible position
while low <= high :
# what needs to be repeated?
# is the value at the midpoint the thing I'm looking for
mid = (low+high)//2
if searchlist[mid] == key:
return mid
# check is our key higher or lower than the value at the midpoint
if searchlist[mid] > key:
# our range should be changed from the low to the mid
high = mid - 1
else:
# our key is bigger than the value at the middle,
# so look in the upper range
low = mid + 1
return -1
card.py 2/7
[top][prev][next]
import test
class Card:
"""
A class to represent a standard playing card. The ranks are ints:
2-10 for numbered cards, 11=Jack, 12=Queen, 13=King, 14=Ace.
The suits are strings: 'clubs', 'spades', 'hearts', 'diamonds'.
"""
def __init__(self, rank, suit):
"Constructs a new Card object with the given rank (an int) and suit (a string)."
self._rank = rank
self._suit = suit
def __str__(self):
"Returns a string describing the card as 'rank of suit'."
result = ""
if self._rank == 11:
result += "Jack"
elif self._rank == 12:
result += "Queen"
elif self._rank == 13:
result += "King"
elif self._rank == 14:
result += "Ace"
else:
result += str(self._rank)
result += " of " + self._suit
return result
def getRank(self):
"Returns rank."
return self._rank
def getSuit(self):
"Returns suit."
return self._suit
def getRummyValue(self):
"Returns the value of the card in the game of Rummy."
# using the helper method may not be the best way
# to implement this, but want to show what we can do.
if self._isFaceCard(): # handles face cards
return 10
elif self._rank == 14: # handles Ace
return 15
elif self._rank == 10: # handles 10
return 10
else:
return 5
def __eq__(self, other):
"""Returns true if this object and other are equivalent
based on their rank and suit"""
# verify that self and other are the same type
if type(self) != type(other):
return False
# do comparison
return self._rank == other._rank and self._suit == other._suit
def __lt__(self, other):
""" Compares Card objects by their rank"""
# verify that self and other are the same type
if type(self) != type(other):
return False
# do comparison
return self._rank < other._rank
def _isFaceCard(self):
"Returns True iff the card is a face card."
if self._rank > 10 and self._rank < 14:
return True
return False
def main():
c1 = Card(14, "spades")
print(c1)
c2 = Card(13, "hearts")
print(c2)
c3 = Card(2, "diamonds")
print(c3)
# test getRummyValue
test.testEqual( c1.getRummyValue(), 15 )
test.testEqual( c2.getRummyValue(), 10 )
test.testEqual( c3.getRummyValue(), 5 )
# test equals and less than
test.testEqual( c1 == c2, False)
test.testEqual( c1 < c2, False)
test.testEqual( c2 < c1, True)
testCases = [ c1, c2, c3]
print("\nTested cards in sorted order:")
testCases.sort()
for card in testCases:
print(card)
# Since I am probably going to import this script into another script,
# I only want to call main() when it's *not* imported
if __name__ == '__main__':
main()
linear_and_binary_search.py 3/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 true iff key is in the list of integers searchlist"
for elem in searchlist:
if elem == key:
return True
return False
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 4/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()
our_search.py 5/7
[top][prev][next]
import test
def binarySearch(searchlist, key):
"""
Pre: searchlist is a list of integers in sorted order.
Returns the position of key (an integer) in the list of
integers (searchlist) or -1 if not found
"""
low = 0
high = len(searchlist) - 1
# while
while low <= high:
# find the mid point and the value at the mid point
mid = (low+high)//2
valueAtMid = searchlist[mid]
# determine if the key is higher or lower than the value at the mid
if key > valueAtMid:
myList = [-3, 0, 0, 1, 2, 7, 8, 9]
test.testEqual( binarySearch(searchlist, 8), 6 )
test.testEqual( binarySearch(searchlist, 6), -1 )
search_compare.py 6/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]
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 integers
print("Creating list of size", NUM_ENTRIES*2, "starting at 1 and incrementing by 2")
print()
print("{:6s}| {:14s}".format("","# Comparisons"))
print("{:6s}| {:>6s} {:>6s}".format("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 7/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()
Generated by GNU Enscript 1.6.6.