Contents

  1. caesar_bycounter.py
  2. card3.py
  3. card_byid.py
  4. command_line_args.py
  5. counter2.py
  6. counter.py

caesar_bycounter.py 1/6

[
top][prev][next]
# Name removed to protect the innocent
# Modified by CS111 to use Counter class
#

from counter import *

MIN_KEY=-25
MAX_KEY=25
A_VAL = ord('a')
Z_VAL = ord('z')

def main():
    text=raw_input("Enter some text: ")
    key=input("Enter an integer key (between "+ str(MIN_KEY) +" and " + str(MAX_KEY) +"): ")
    if key < MIN_KEY or key > MAX_KEY:
        print "Key must be within range", MIN_KEY,"and", MAX_KEY
    else: 
        text = text.lower()
        message= encoder(text,key)
        print message

#encoder takes in some lowercase text and integer key and returns encoded
#message, retaining spaces between words
def encoder(text, key):
    message=""
    for ch in text:
        if ch == " ":
            message+=" "
        else:
            message += translateLetter(ch,key)
    return message

#takes as parameters a lowercase letter and integer key and returns the
#encoded letter
def translateLetter(letter, key):
    # create a counter object with a range from the ASCII values of 'a' to 'z'
    ascii_counter = Counter(ord('a'), ord('z'))
    # set the counter to the letter to encode
    ascii_counter.setValue(ord(letter))
    
    # translate the ASCII value
    if key > 0:
        ascii_counter.increment(key)
    else:
        ascii_counter.decrement(key*-1)
        
    encoded_value = ascii_counter.getValue()
    
    # translate from ASCII to the letter
    transLetter = chr(encoded_value)
    return transLetter
           
#call main function
main()

card3.py 2/6

[
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):
        if self.rank == 14:
            return 1
        elif self.rank > 10:
            return 10
        else:
            return self.rank

    def rummyValue(self):
        if 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
        #print self, other
        if self.rank < other.getRank():
            #print "less"
            return -1
        elif self.rank > other.getRank():
            #print "greater"
            return 1
        else:
            return 0
        

def main():
    c3 = Card(3, "hearts")
    print "c1 =", c3
    c2 = Card(13, "hearts")
    print "c2 =", c2
    c1 = Card(3, "spades")
    print "c3 =", c1
    
    print "\nTest _cmp_ method..."
    print c1, "__cmp__", c2, "-->", c1.__cmp__(c2)
    print c3, "__cmp__", c1, "-->", cmp(c3,c1)
    
    #If you don't define a __cmp__ method, then the default behavior is to
    # compare memory addresses.
    
    print c1,">",c2,"?", c1 > c2
    print c1,">",c3,"?", c1 > c3
    print c2, ">", c3, "?", c2 > c3
    
if __name__ == '__main__':
    main()

card_byid.py 3/6

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

command_line_args.py 4/6

[
top][prev][next]
# Demonstrate use of command-line arguments
# by Sara Sprenkle
# Usage: python command_line_args.py filename

import sys

PROG_ARG_LOC=0
FILENAME_ARG_LOC=1

# Make sure there are sufficient arguments.
if len(sys.argv) < 2:
    print "Error: invalid number of command-line arguments"
    print "Usage: python", sys.argv[PROG_ARG_LOC],"<filename>"
    sys.exit(1)
    
filename = sys.argv[FILENAME_ARG_LOC]
print "We will use file", filename, "as input"


counter2.py 5/6

[
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 6/6

[
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."
        rep = "Value: " + str(self.value)
        rep += " Low: " + str(self.low)
        rep += " High: " + str(self.high)
        return rep

    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. """
        num_wraps = 0
        for x in xrange(amount):
            if self.value < self.high:
                self.value += 1
            else:
                self.value = self.low
                num_wraps += 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. """
        num_wraps = 0
        for x in xrange(0, amount, 1):
            if self.value > self.low:
                self.value -= 1
            else:
                self.value = self.high
                num_wraps += 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()

Generated by GNU enscript 1.6.4.