Contents

  1. ./card.py
  2. ./linear_and_binary_search.py
  3. ./linear_search.py
  4. ./test.py

./card.py 1/4

[
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.
        Returns True if this Card's rank is smaller than the 
        other Card's 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)
    
    ####
    # Just focusing on tests for the newly added code
    ####
    
    anotherAceOfSpades = Card(14, "spades")

    # test equals and less than
    test.testEqual( c1 == c2, False)
    test.testEqual( c1 == "Ace of spades", False)
    test.testEqual( c1 == anotherAceOfSpades, True)
    test.testEqual( c1 < c2, False)
    test.testEqual( c2 < c1, True)
    test.testEqual( c1 < anotherAceOfSpades, False)
    test.testEqual( c1 > anotherAceOfSpades, False)

    
    testCases = [ c1, c2, c3 ]
    print("\nTested cards in sorted order:")
    testCases.sort()
    for card in testCases:
        print(card)
    test.testEqual( testCases, [ c3, c2, c1] )
    
# 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 2/4

[
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 3/4

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

./test.py 4/4

[
top][prev][next]
# From How to Think Like a Computer Scientist textbook

def testEqual(actual,expected,places=5):
    '''
    Does the actual value equal the expected value?
    For floats, places indicates how many places, right of the decimal, must be correct
    '''
    if isinstance(expected,float):
        if abs(actual-expected) < 10**(-places):
            print('\tPass')
            return True
    else:
        if actual == expected:
            print('\tPass')
            return True
    print('\tTest Failed: expected {} but got {}'.format(expected,actual))
    return False

Generated by GNU Enscript 1.6.5.90.