Question 1 (Sarah)


In [11]:
class Time(object):
    """Represents the time of day.
    attributes: hour, minute, second
    """
    def __init__(self, hour=0, minute=0, second=0):
        self.second = hour * 3600 + minute * 60 + second

    def __str__(self):
        minutes, second = divmod(self.second, 60)
        hour, minute = divmod(minutes, 60)
        return '{:02d}:{:02d}:{:02d}'.format(hour, minute, second)


    def __cmp__(self, other):
        t1=self.second
        t2=other.second
        
        return cmp(t1,t2) 

t1=Time(20,15,5)
t2=Time(20,15,5)
    
#print t1.second
#print t2

print t1<t2


False

In [14]:
#t1.__cmp__(t2)
Time.__cmp__(t1,t2)


Out[14]:
0

In [15]:
type(t1)


Out[15]:
__main__.Time

Question 2 (Dan)


In [33]:
import random

class Card(object):
    """Represents a standard playing card."""

    suit_names = ['Clubs', 'Diamonds', 'Hearts', 'Spades']
    rank_names = [None, 'Ace', '2', '3', '4', '5', '6', '7', 
              '8', '9', '10', 'Jack', 'Queen', 'King']
    
    def __init__(self, suit=0, rank=2):
        self.suit = suit
        self.rank = rank

    def __str__(self):
        return '%s of %s' % (Card.rank_names[self.rank],
                             Card.suit_names[self.suit])
    
    def __cmp__(self, other):
        t1 = self.suit, self.rank
        t2 = other.suit, other.rank
        return cmp(t1, t2)
    
    
class Deck(object):

    def __init__(self):
        self.cards = []
        for suit in range(4):
            for rank in range(1, 14):
                card = Card(suit, rank)
                self.cards.append(card)

    def shuffle(self):
        random.shuffle(self.cards)
        
    def __str__(self):
        res = []
        for card in self.cards:
            res.append(str(card))
        return '\n'.join(res)

    def sort(self):
        self.cards.sort()

Creating a deck and shuffling it.


In [35]:
d = Deck()
d.shuffle()
print(d)


9 of Hearts
Ace of Spades
4 of Spades
2 of Clubs
Ace of Clubs
10 of Hearts
8 of Spades
Jack of Diamonds
7 of Clubs
6 of Clubs
4 of Hearts
7 of Diamonds
10 of Spades
Jack of Clubs
7 of Hearts
Queen of Diamonds
Jack of Spades
2 of Diamonds
6 of Diamonds
5 of Spades
6 of Spades
Queen of Hearts
Queen of Clubs
Ace of Hearts
2 of Spades
2 of Hearts
5 of Clubs
3 of Diamonds
3 of Hearts
King of Clubs
3 of Spades
9 of Clubs
9 of Diamonds
9 of Spades
King of Spades
4 of Diamonds
7 of Spades
8 of Clubs
10 of Clubs
8 of Diamonds
5 of Diamonds
8 of Hearts
3 of Clubs
6 of Hearts
Queen of Spades
4 of Clubs
10 of Diamonds
King of Diamonds
Ace of Diamonds
Jack of Hearts
King of Hearts
5 of Hearts

Now sorting the deck.


In [36]:
d.sort()
print(d)


Ace of Clubs
2 of Clubs
3 of Clubs
4 of Clubs
5 of Clubs
6 of Clubs
7 of Clubs
8 of Clubs
9 of Clubs
10 of Clubs
Jack of Clubs
Queen of Clubs
King of Clubs
Ace of Diamonds
2 of Diamonds
3 of Diamonds
4 of Diamonds
5 of Diamonds
6 of Diamonds
7 of Diamonds
8 of Diamonds
9 of Diamonds
10 of Diamonds
Jack of Diamonds
Queen of Diamonds
King of Diamonds
Ace of Hearts
2 of Hearts
3 of Hearts
4 of Hearts
5 of Hearts
6 of Hearts
7 of Hearts
8 of Hearts
9 of Hearts
10 of Hearts
Jack of Hearts
Queen of Hearts
King of Hearts
Ace of Spades
2 of Spades
3 of Spades
4 of Spades
5 of Spades
6 of Spades
7 of Spades
8 of Spades
9 of Spades
10 of Spades
Jack of Spades
Queen of Spades
King of Spades

Question 3 (Liu)


In [1]:
import random


class Card(object):
    """Represents a standard playing card.
    
    Attributes:
      suit: integer 0-3
      rank: integer 1-13
    """

    suit_names = ["Clubs", "Diamonds", "Hearts", "Spades"]
    rank_names = [None, "Ace", "2", "3", "4", "5", "6", "7", 
              "8", "9", "10", "Jack", "Queen", "King"]

    def __init__(self, suit=0, rank=2):
        self.suit = suit
        self.rank = rank

    def __str__(self):
        """Returns a human-readable string representation."""
        return '%s of %s' % (Card.rank_names[self.rank],
                             Card.suit_names[self.suit])

    def __cmp__(self, other):
        """Compares this card to other, first by suit, then rank.

        Returns a positive number if this > other; negative if other > this;
        and 0 if they are equivalent.
        """
        t1 = self.suit, self.rank
        t2 = other.suit, other.rank
        return cmp(t1, t2)


class Deck(object):
    """Represents a deck of cards.

    Attributes:
      cards: list of Card objects.
    """
    
    def __init__(self):
        self.cards = []
        for suit in range(4):
            for rank in range(1, 14):
                card = Card(suit, rank)
                self.cards.append(card)

    def __str__(self):
        res = []
        for card in self.cards:
            res.append(str(card))
        return '\n'.join(res)

    def add_card(self, card):
        """Adds a card to the deck."""
        self.cards.append(card)

    def remove_card(self, card):
        """Removes a card from the deck."""
        self.cards.remove(card)

    def pop_card(self, i=-1):
        """Removes and returns a card from the deck.

        i: index of the card to pop; by default, pops the last card.
        """
        return self.cards.pop(i)

    def shuffle(self):
        """Shuffles the cards in this deck."""
        random.shuffle(self.cards)

    def sort(self):
        """Sorts the cards in ascending order."""
        self.cards.sort()

    def move_cards(self, hand, num):
        """Moves the given number of cards from the deck into the Hand.

        hand: destination Hand object
        num: integer number of cards to move
        """
        for i in range(num):
            hand.add_card(self.pop_card())
            
    def deal_hands(self, num_of_hands, num_of_cards):
        hands_list = []
        for i in range(num_of_hands):
            new_hand = Hand(str(i + 1))
            self.move_cards(new_hand, num_of_cards)
            hands_list.append(new_hand)
        return hands_list


class Hand(Deck):
    """Represents a hand of playing cards."""
    
    def __init__(self, label=''):
        self.cards = []
        self.label = label

In [2]:
deck = Deck()
deck.shuffle()

num_of_hands = 5
num_of_cards = 2
hands_list = deck.deal_hands(num_of_hands, num_of_cards)
for single_hand in hands_list:
    print 'Hand No. ' + single_hand.label + ':'
    print single_hand
    print


Hand No. 1:
Queen of Clubs
3 of Spades

Hand No. 2:
9 of Clubs
7 of Diamonds

Hand No. 3:
Ace of Spades
2 of Spades

Hand No. 4:
7 of Spades
Ace of Clubs

Hand No. 5:
3 of Hearts
Ace of Diamonds

Question 5 (Dan)

Original code


In [3]:
"""This module contains code from
Think Python by Allen B. Downey
http://thinkpython.com

Copyright 2012 Allen B. Downey
License: GNU GPLv3 http://www.gnu.org/licenses/gpl.html

"""

import sys
import string
import random

# global variables
suffix_map = {}        # map from prefixes to a list of suffixes
prefix = ()            # current tuple of words


def process_file(filename, order=2):
    """Reads a file and performs Markov analysis.

    filename: string
    order: integer number of words in the prefix

    Returns: map from prefix to list of possible suffixes.
    """
    fp = open(filename)
    skip_gutenberg_header(fp)

    for line in fp:
        for word in line.rstrip().split():
            process_word(word, order)


def skip_gutenberg_header(fp):
    """Reads from fp until it finds the line that ends the header.

    fp: open file object
    """
    for line in fp:
        if line.startswith('*END*THE SMALL PRINT!'):
            break


def process_word(word, order=2):
    """Processes each word.

    word: string
    order: integer

    During the first few iterations, all we do is store up the words; 
    after that we start adding entries to the dictionary.
    """
    global prefix
    if len(prefix) < order:
        prefix += (word,)
        return

    try:
        suffix_map[prefix].append(word)
    except KeyError:
        # if there is no entry for this prefix, make one
        suffix_map[prefix] = [word]

    prefix = shift(prefix, word)


def random_text(n=100):
    """Generates random wordsfrom the analyzed text.

    Starts with a random prefix from the dictionary.

    n: number of words to generate
    """
    # choose a random prefix (not weighted by frequency)
    start = random.choice(suffix_map.keys())
    
    for i in range(n):
        suffixes = suffix_map.get(start, None)
        if suffixes == None:
            # if the start isn't in map, we got to the end of the
            # original text, so we have to start again.
            random_text(n-i)
            return

        # choose a random suffix
        word = random.choice(suffixes)
        print word,
        start = shift(start, word)


def shift(t, word):
    """Forms a new tuple by removing the head and adding word to the tail.

    t: tuple of strings
    word: string

    Returns: tuple of strings
    """
    return t[1:] + (word,)


def main(name, filename='', n=100, order=2, *args):
    try:
        n = int(n)
        order = int(order)
    except:
        print 'Usage: randomtext.py filename [# of words] [prefix length]'
    else: 
        process_file(filename, order)
        random_text(n)


if __name__ == '__main__':
    main(_, filename='emma.txt')


the greater part of the street, and there she had the power as well as she entered the house. I merely called, because I thought you meant to say any thing. . . . . . Indeed I must speak to Dr. and Mrs. Wallis does them full justice--only we do to rouse them? Any nonsense will serve. They _shall_ talk. Ladies and gentlemen--I am ordered by Miss Bates's voice, something was to afford at Randalls one day;--even Mr. Woodhouse had been afraid it would be no possibility of good fortune. I hope he does," replied Mr. Knightley; "I have

All of the functions shoved into a class


In [13]:
"""This module contains code from
Think Python by Allen B. Downey
http://thinkpython.com

Copyright 2012 Allen B. Downey
License: GNU GPLv3 http://www.gnu.org/licenses/gpl.html

"""

import sys
import string
import random

class Markov(object):
    
    def __init__(self):
        self.suffix_map = {}  # map from prefixes to a list of suffixes
        self.prefix = ()      # current tuple of words
        
    def process_file(self, filename, order=2):
        """Reads a file and performs Markov analysis.

        filename: string
        order: integer number of words in the prefix

        Returns: map from prefix to list of possible suffixes.
        """
        fp = open(filename)
        self.skip_gutenberg_header(fp)

        for line in fp:
            for word in line.rstrip().split():
                self.process_word(word, order)


    def skip_gutenberg_header(self, fp):
        """Reads from fp until it finds the line that ends the header.

        fp: open file object
        """
        for line in fp:
            if line.startswith('*END*THE SMALL PRINT!'):
                break


    def process_word(self, word, order=2):
        """Processes each word.

        word: string
        order: integer

        During the first few iterations, all we do is store up the words; 
        after that we start adding entries to the dictionary.
        """

        if len(self.prefix) < order:
            self.prefix += (word,)
            return

        try:
            self.suffix_map[self.prefix].append(word)
        except KeyError:
            # if there is no entry for this prefix, make one
            self.suffix_map[self.prefix] = [word]

        self.prefix = self.shift(prefix, word)


    def random_text(self, n=100):
        """Generates random wordsfrom the analyzed text.

        Starts with a random prefix from the dictionary.

        n: number of words to generate
        """
        # choose a random prefix (not weighted by frequency)
        start = random.choice(self.suffix_map.keys())

        for i in range(n):
            suffixes = self.suffix_map.get(start, None)
            if suffixes == None:
                # if the start isn't in map, we got to the end of the
                # original text, so we have to start again.
                random_text(n-i)
                return

            # choose a random suffix
            word = random.choice(suffixes)
            print word,
            start = self.shift(start, word)


    def shift(self, t, word):
        """Forms a new tuple by removing the head and adding word to the tail.

        t: tuple of strings
        word: string

        Returns: tuple of strings
        """
        return t[1:] + (word,)


def main(name, filename='', n=100, order=2, *args):
    try:
        n = int(n)
        order = int(order)
    except:
        print 'Usage: randomtext.py filename [# of words] [prefix length]'
    else: 
        m = Markov()
        m.process_file(filename, order)
        m.random_text(n)


if __name__ == '__main__':
    main(_, filename='emma.txt')


has own powers, and yet it is honourable.-- Yes, honourable, I think, but I believed none of their being left to itself. She, therefore, said no more; and Emma passed into it with the greatest alacrity and enjoyment. "What an exquisite flutter of spirits which would probably repent it. Six years hence, if he could never allow you to make apologies, excuses, to urge something for a young man, and I shall hear about you all," said he; so I put it down; but when they left her long, by no means yet reconciled to his companions; and he had

Question 6


In [ ]: