1 a censor class class censor: def __ init __ (self,replacers='!@$%&?', badwords=[]):...
TRANSCRIPT
1
A Censor Class
class Censor: def __init__(self,replacers='!@$%&?', badwords=[]): self.badwords = badwords self.replacers = replacers
def input_badwords(self,fpath): # build the self.badwords list from file of whitespace # separated words f = open(fpath,'r') S = f.read() f.close() self.badwords = S.split()
def output_badwords(self,fpath): # store the self.badwords list in file, #separated by spaces S = ' '.join(self.badwords) f = open(fpath,'w') f.write(S) f.close()
2
A Censor Class
def addwords(self,word_list): # add words from word_list to self.badwords self.badwords = self.badwords+word_list
# or: self.badwords.extend(word_list)
def remove_words(self,word_list): # remove words in word_list from self.badwords self.badwords = [w for w in self.badwords if w not in word_list]
# or: # for w in word_list: # while w in self.badwords: # self.badwords.remove(w)
3
A Censor Class
def censor_word(self,n) # return a length-n word composed of randomly chosen # symbols from self.replacers w = '' for i in range(n): w += random.choice(self.repeaters) return w
def censor_word2(self,n): # return a length-n word composed of randomly chosen # symbols from self.replacers, no two consecutive letters the same w = random.choice(self.repeaters) for i in range(n-1): new = random.choice(self.repeaters) while new == w[-1]: new = random.choice(self.repeaters) w += new return w
def censor_file(self,fpath): # Write a new file named fpath+'.censored' whose contents are the contents of the # file at fpath with each word that is in self.badwords replaced by an equal-length # word of randomly chosen letters from self.replacers pass
4
A Censor Class
def censor_file(self,fpath): # Write a new file named fpath+'.censored' whose contents are the contents of the # file at fpath with each word that is in self.badwords replaced by an equal-length # word of randomly chosen letters from self.replacers
inf = open(fpath,'r') L = inf.read().split() inf.close()
K = [] for w in L:
if w in self.badwords: K.append(censor_word(len(w)))
else: K.append(w)
outf = open(fpath+'.censored','w') outf.write(' '.join(K)) outf.close()
badword_filename = input("Enter the name of the bad words file: ")txt_filename = input("Enter the name of the file to be censored: ")
C = Censor()
C.input_badwords(badword_filename)C.censor_file(txt_filename)
5
The Card Class
# card.py# defines a minimal class to represent poker cards
class Card: '''Represents cards from a poker deck. The rank is an integer between 1 and 13 and the suit is one of 'c','d','h','s'.
'''
def __init__(self,rank,suit): self.rank = rank self.suit = suit
def getRank(self): return self.rank
def getSuit(self): return self.suit
6
The Card Class
# Card class definition continued
def BJValue(self): # Blackjack card value if self.rank <= 10: return self.rank else: return 10
7
The Card Class
# Card class definition continued
def __str__(self): # string to be printed when the card s = '' # appears in a print statement
if self.rank == 1: s += 'Ace'
elif 2 <= self.rank <= 10: s += str(self.rank)
elif self.rank == 11: s += 'Jack'
elif self.rank == 12: s += 'Queen'
else: s += 'King'
s += ' of '
8
The Card Class
# Card class definition continued
# def _ _str_ _(self) continued
if self.suit == 'c': s += 'Clubs'
elif self.suit == 'd': s += 'Diamonds'
elif self.suit == 'h': s += 'Hearts'
else: s += 'Spades'
return s
9
The Card Class
# Card class definition continued def __lt__(self,other): # Makes possible comparison via <
if self.rank == other.rank: return self.suit < other.suit
elif self.rank == 1: return False
elif other.rank == 1: return True
else: return self.rank < other.rank
def __ eq__(self,other): # Makes possible comparison via == return self.rank == other.rank and \ self.suit == other.suit
10
The Hand Class
# poker_hand.py# class to represent a hand occurring in a poker gamefrom card import Cardclass Hand: def __init__(self,card_list): self.cards = card_list # must have length 5
def maxRank(self): # returns a card of maximum rank in self.card_list # if more than one card has that rank, returns the # card with the highest suit # where 'c' < 'd' < 'h' < 's' # (which is just the alphabetic order!)
return sorted(self.cards)[-1]
11
The Hand Class
def poker_description(self): # returns one of the following strings: # 'Royal Flush','Straight Flush','Four of a Kind', # 'Full House','Flush', 'Straight', 'Three of a Kind', # 'Two Pair','Pair', 'High Card' is_flush = len({c.getSuit() for c in self.cards}) ==1 high_card = self.maxRank() high_rank = high_card.getRank() rank_list = sorted([c.getRank() for c in self.cards]) if rank_list == list(range(high_rank-4,high_rank+1)): is_straight = True elif rank_list == [1,10,11,12,13]: is_straight = True else: is_straight = False
12
The Hand Class
# poker_description definition continued is_flush = len({c.getSuit() for c in self.cards}) ==1
high_card = self.maxRank() high_rank = high_card.getRank()
rank_list = sorted([c.getRank() for c in self.cards]) if rank_list == list(range(high_rank-4,high_rank+1)): is_straight = True elif rank_list == [1,10,11,12,13]: is_straight = True else: is_straight = False
13
The Hand Class
# poker_description definition continued if is_flush and is_straight: if high_rank == 1: return "Royal Flush" else: return "Straight Flush" if is_flush: return "Flush" if is_straight: return "Straight"
14
The Hand Class
# poker_description definition continued rank_counts = sorted([rank_list.count(k) for k in set(rank_list)]) if rank_counts == [1,4]: return "Four of a Kind" elif rank_counts == [2,3]: return "Full House" elif rank_counts == [1,1,3]: return "Three of a Kind" elif rank_counts == [1,2,2]: return "Two Pair" elif rank_counts == [1,1,1,2]: return "Pair" else: return "High Card" def __str__(self): return '\n'.join([str(c) for c in self.cards])
15
The Deck Class
# deck.py# class to represent a deck of cards during a game of poker
import random,sysfrom card import Cardfrom poker_hand import Hand
# List of cards as found when a new deck is opened.newDeckList = []for s in ['c','d','h','s']: for r in range(1,14): newDeckList.append(Card(r,s))
16
The Deck Class
# deck.py (continued)
class Deck:
def __init__(self,cardList=newDeckList): self.cardList = cardList self.top = 0
def open_new_deck(self): self.cardList = newDeckList self.top = 0
def shuffleDeck(self): random.seed() random.shuffle(self.cardList)
17
The Deck Class
# deck.py (continued)# class Deck, continued def dealHand(self): # cards removed from deck as they are dealt if len(self.cardList) < 5: return None self.top += 5 return Hand(self.cardList[self.top-5:self.top])
def cards_left(self): return 52-self.top
def generateRandomHand(self): # cards not removed from Deck; no need to shuffle L = random.sample(self.cardList,5) return Hand(L)
18
The Deck Class
# deck.py (continued)
if __name__ == '__main__':
mydeck = Deck()
print('New deck has',mydeck.cards_left(), 'cards in the deck')
print('Now shuffle the cards and deal a hand:')
mydeck.shuffleDeck()
myhand = mydeck.dealHand()
print()
print(myhand)
print()
print('That leaves',mydeck.cards_left(), 'cards in the deck')
print()
19
The Deck Class
# deck.py (continued)
mydeck.open_new_deck()
print('Opened a new deck of cards')
print('Lets generate a random hand', 'without removing the cards')
newhand = mydeck.generateRandomHand()
print()
print(newhand)
20
card_game_simulator
from deck import Deck
from poker_hand import Hand
if __name__ == '__main__':
player_names = ['Terry','Ed','Ralph','Bernie']
player_hands = {}
for p in player_names:
player_hands[p] = None
d = Deck()
d.shuffleDeck()
21
card_game_simulator
from deck import Deck
from poker_hand import Hand
player_names = ['Terry','Ed','Ralph','Bernie']
player_hands = {}
for p in player_names:
player_hands[p] = None
d = Deck()
d.shuffleDeck()
for p in player_names:
player_hands[p] = d.dealHand()
print(p,player_hands[p].poker_description())
print('\n')
22
card_game_simulator
Freq = {}
hand_values = ['Royal Flush','Straight Flush','Four of a Kind', 'Full House','Flush', 'Straight', 'Three of a Kind','Two Pair','Pair','High Card' ]
for t in hand_values:
Freq[t] = 0
d = Deck()
for i in range(100000):
h = d.generateRandomHand()
Freq[h.poker_description()] += 1
for t in hand_values:
print(t,':',Freq[t])
23
Assignment 5: The Cards Project
Out of 100,000 hands: