Contents

  1. card.py
  2. search2.py
  3. search_compare.py
  4. search_divide.py
  5. search.py

card.py 1/5

[
top][prev][next]
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 rummyValue(self):
        "Returns the card's rummy value"
        if self.getRank() < 10: # handles number cards
            return 5
        elif self.rank == 14: # handles Ace
            return 15
        else: # handles 10 and face cards
            return 10
            
    def __eq__(self, other):
        """Returns true if this object and other are equivalent
        based on their suit and rank"""
        
        # 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 totalOrderCardKeyFunction(card):
    """Returns the key to be used for comparison.
    Parameter: card of type Card
    """
    
    # creates a string out of the attributes of the Card that is used to compare
    # the Cards.  
    
    # This key means that the cards will be ordered by their
    # rank and then their suit.
    
    #key = "%2d %s" % (card.getRank(), card.getSuit())
    
    # This key means that cards will be ordered by their suit
    # then their rank
    key = "%s %2d" % (card.getSuit(), card.getRank())
    
    # Is one way to sort better than the other?
    
    return key
    
def main():
    cards = []
    
    for suit in ["clubs","hearts","diamonds","spades"]:
        for rank in range(2,15):
            cards.append(Card(rank, suit))

    # sort the cards using the key specified by the function
    cards.sort(key=totalOrderCardKeyFunction)
    
    print("The ordered cards are: ")
    for c in cards:
        print(c)
    
    
# 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()

search2.py 2/5

[
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()

search_compare.py 3/5

[
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" % ("","# 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" % (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 4/5

[
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()

search.py 5/5

[
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()

Generated by GNU Enscript 1.6.6.