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
In [14]:
#t1.__cmp__(t2)
Time.__cmp__(t1,t2)
Out[14]:
In [15]:
type(t1)
Out[15]:
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)
Now sorting the deck.
In [36]:
d.sort()
print(d)
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
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')
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')
In [ ]: