Contents

  1. caesar_with_counter.py
  2. card4.py
  3. card_byid.py
  4. counter2.py
  5. counter.py

caesar_with_counter.py 1/5

[
top][prev][next]
# Encodes a phrase entered by a user
# Modified by CS111 to use Counter class

import sys
from counter import *

KEY_BOUND=25
MIN_ASCII=ord('a')
MAX_ASCII=ord('z')
ASCII_SHIFT = 26

def main():
    print "This program encodes and decodes Caesar ciphers\n"

    text = raw_input("Enter some text: ")
    key = input("Enter an integer key (between -25 and 25): ")
    
    # make sure it's a valid key
    if key < -KEY_BOUND or key > KEY_BOUND:
        print "Invalid key!"
        sys.exit(1)
    
    message = encoder(text,key)
    print message

# takes in some text and integer key (between -25 and 25,
# inclusive) and returns encoded message
def encoder(text,key):
    message=""
    for ch in text:
        if ch == " ":
            encode= " "
            message+=encode
        else:
            message += translateLetter(ch,key)
    return message

# takes in a letter and integer key (between -25 and
# 25, inclusive) and returns the encoded letter
def translateLetter(letter,key):
    
    counter = Counter( MIN_ASCII, MAX_ASCII, ord(letter) )
    if key > 0:
        counter.increment(key)
    else:
        counter.decrement(key)
        
    newASCIIValue = counter.getCurrentValue()
    
    return chr(newASCIIValue)
    
#call main function
main()

card4.py 2/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):
        "Constructor for class Card takes int rank and string suit."
        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 blackJackValue(self):
        "Returns the blackjack value of this card."
        if self.rank == 14:
            return 1
        elif self.rank > 10:
            return 10
        else:
            return self.rank
            
    def _isFaceCard(self):
        "Returns True iff this card is a face card (K, Q, or J)."
        if self.rank > 10 and self.rank < 14:
            return True
        return False

    def rummyValue(self):
        "Returns the value of this card in Rummy."
        if self._isFaceCard():
            return 10
        elif self.rank == 14:
            return 15
        elif self.rank == 10:
            return 10
        else:
            return 5
    
        
    def __cmp__(self, other):
        """ Compares Card objects by their ranks """
        # Could compare by black jack value or rummy value
        if self.rank < other.rank:
            return -1
        if self.rank == other.rank:
            return 0
        return 1
        
        # Equivalent to : 
        #    return self.rank - other.rank
        
            
def main():
    c1 = Card(14, "spades")
    print c1
    print "Black Jack Value", c1.blackJackValue()
    
    c2 = Card(13, "hearts")
    print c2
    print "Black Jack Value", c2.blackJackValue()
    
    #print c2._isFaceCard()
    
    c3 = Card(3, "diamonds")
    print c3
    print "Rummy value", c3.rummyValue()
    
    # Demonstrate use of __cmp__ method
    print "\nDemonstrate use of __cmp__ method:"
    print c2, "less than", c3, "?", c2 < c3  # should be False
    print c3, "less than", c2, "?", c3 < c2  # should be True
    
    myCards = [c1, c2, c3]
    myCards.sort()
    
    print "\nSorted cards: "
    for card in myCards:
        print card
    
if __name__ == '__main__':
    main()

card_byid.py 3/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'.
    """
    
    # card ids go from 2 to 55
    
    def __init__(self, rank, suit):
        "Constructor for class Card takes int rank and string suit."
        self.cardid = rank
        if suit == "clubs":
            self.cardid += 13
        elif suit == "hearts":
            self.cardid += 26
        elif suit == "diamonds":
            self.cardid += 39

    def __str__(self):
        "Returns a string describing the card as 'rank of suit'."
        result = ""
        rank = self.getRank()
        if rank == 11:
            result += "Jack"
        elif rank == 12:
            result += "Queen"
        elif rank == 13:
            result += "King"
        elif rank == 14:
            result += "Ace"
        else:
            result += str(rank)
        result += " of " + self.getSuit()
        return result

    def getRank(self):
        "Returns rank."
        return (self.cardid-2) % 13 + 2

    def getSuit(self):
        "Returns suit."
        suits = ["spades", "clubs", "hearts", "diamonds"]
        whichsuit = (self.cardid-2)/13
        return suits[whichsuit]

    def blackJackValue(self):
    	"Returns the value of the card in Black Jack"
        if self.getRank() == 14:
            # alternatively, this could be 11
            return 1
        elif self.getRank() > 10:
            return 10
        else:
            return self.getRank()

    def rummyValue(self):
        "Returns the value of the card in Rummy"
        if self.getRank() <= 9:
            return 5
        elif self.getRank() < 14:
            return 10
        else:
            return 15

def main():
    c1 = Card(14, "spades")
    print c1
    print c1.getRank()
    print "Black Jack Value", c1.blackJackValue()
    print "Rummy Value", c1.rummyValue()
    c2 = Card(13, "hearts")
    print c2
    print c2.getRank()
    print "Black Jack Value", c2.blackJackValue()
    print "Rummy Value", c2.rummyValue()
    
if __name__ == '__main__':
    main()


counter2.py 4/5

[
top][prev][next]
class Counter:

    """ A class to represent a counter that wraps around from a high value back
    to its low value."""

    def __init__(self, low, high):
        """ Creates a Counter object with the given low and high values """
        self.low = low
        self.high = high
        self.value = low

    def __str__(self):
        "Returns a string representation of this Counter object."
        result = "Value: " + str(self.value)
        result += " Low: " + str(self.low)
        result += " High: " + str(self.high)
        return result

    def increment(self, amount=1):
        """ Increment the counter by the given amount, wrapping around to low
        again, if necessary. Returns number of times had to wrap around. """
        
        range_of_nums = self.high-self.low+1
        
        # the number of times this will wrap around
        num_wraps = amount/range_of_nums
        
        # the "real" amount to increment by
        real_inc_amount = amount%range_of_nums
        
        self.value += real_inc_amount
        if self.value > self.high:
            self.value = self.low + (self.value - self.high - 1)

        return num_wraps
        
    def decrement(self, amount=1):
        """ Decrement the counter by the given amount (a positive number),
        wrapping around to high again, if necessary. Returns number of times had
        to wrap around. """
        range_of_nums = self.high-self.low+1
        num_wraps = amount/range_of_nums
        real_dec_amount = amount % range_of_nums
        
        self.value -= real_dec_amount
        if self.value < self.low:
            self.value = self.high - (self.low - self.value + 1)

        return num_wraps

    def setValue(self, value):
        """ Sets the counter's value, only if low <= value <= high.  Otherwise,
        prints an error message."""
        if value >= self.low and value <= self.high:
            self.value = value
        else:
            print "ERROR: value must be within range", self.low, "-", \
                  self.high

    def getValue(self):
        return self.value

    def getLow(self):
        return self.low

    def getHigh(self):
        return self.high

def testCounter():
    c = Counter(5,10)
    print c
    c.increment()
    print c
    c.increment(3)
    print "Current value:", c.getValue()
    c.increment(4)
    print c
    print "Increment by 20 --> wraps", c.increment(20), "times"
    print c
    c.decrement()
    print c
    print "Decrement by 20 --> wraps", c.decrement(20), "times"
    print c

#testCounter()


counter.py 5/5

[
top][prev][next]
# By CSCI111

class Counter:
    
    """Represents a counter that has a fixed range. It starts at some low value
    and increments by 1. When it reaches the high value, it wraps back around to
    the minimum value. """
    
    def __init__(self, start, stop, currValue):
        self.start = start
        self.stop = stop
        self.currValue = currValue
    
    def __str__(self):
        stringRep = "Current value: " + str(self.currValue)
        return stringRep
    
    def increment(self, incValue = 1):
        """Increment the counter by the given amount, wrapping around to low
        again, if necessary. Returns number of times had to wrap around."""
        
        # Not the most efficient solution, but it's easy to see that it is
        # correct.
        num_wraps = 0
        for x in xrange(incValue):
            if self.currValue < self.stop:
                self.currValue += 1
            else:
                self.currValue = self.start
                num_wraps += 1
        return num_wraps
        
    def decrement(self, decValue = -1):
        """Increment the counter by the given amount, wrapping around to low
        again, if necessary. Returns number of times had to wrap around."""
        
        # Not the most efficient solution, but it's easy to see that it is
        # correct.
        num_wraps = 0
        for x in xrange(0, decValue, -1):
            if self.currValue > self.start:
                self.currValue -= 1
            else:
                self.currValue = self.stop
                num_wraps -= 1
        return num_wraps

    def getCurrentValue(self):
        'Returns the current value of this Counter object'
        return self.currValue
    
    def getUpperLimit(self):
        'Returns the upper limit of this Counter object'
        return self.stop
        
    def getLowerLimit(self):
        'Returns the lower limit of this Counter object'
        return self.start
        
    def setValue(self, newValue):
        """ 
        precondition: newValue is an integer between the lower and upper
        limit, inclusive.
        Sets the Counter's current value, if the newValue is within the valid
        range. """
        
        if newValue <= self.stop and newValue >= self.start:
            self.currValue = newValue
        else:  
            # Error message
            print newValue, "is not within valid range: ", self.start, self.stop

def main():
    counter = Counter(1, 12, 2)
    print counter
    
    for x in xrange(12):
        counter.increment(13)
        print counter
     
    counter.decrement()
    counter.decrement()
    counter.decrement()

    print counter
  
if __name__ == "__main__":
    main() 

Generated by GNU enscript 1.6.4.