Skip to content

Commit 8409ae7

Browse files
pnojaipnojai
authored andcommitted
Worked in my local at home.
1 parent 79e80b7 commit 8409ae7

12 files changed

Lines changed: 632 additions & 56 deletions

File tree

Lines changed: 110 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,110 @@
1+
print('Define right_justify()...')
2+
def right_justify(s):
3+
right_margin = 70
4+
s_length = len(s)
5+
pad = ' ' * (right_margin - s_length)
6+
print(pad + s)
7+
8+
print('Testing right_justify()...')
9+
right_justify('monty')
10+
right_justify('jai')
11+
right_justify('0123456789'*7)
12+
13+
print('Define do_twice()...')
14+
def do_twice(f, arg):
15+
f(arg)
16+
f(arg)
17+
18+
print('Define print_spam()...')
19+
def print_spam(s):
20+
print('spam'+': '+s)
21+
22+
print('Testing do_twice()...')
23+
do_twice(print_spam, 'spud')
24+
25+
print('Define do_four()...')
26+
def do_four(f, arg):
27+
do_twice(f, arg)
28+
do_twice(f, arg)
29+
30+
print('Testing do_four()...')
31+
do_four(print, 'PnoJai')
32+
33+
print('Exercises 3.3 and 3.4...')
34+
35+
def PrintGridHorizontalBorder(CornerChar, FillHorizontalChar, CellWidth, ColCount):
36+
i = 1
37+
38+
while i <= ColCount:
39+
#print(i)
40+
print(CornerChar + FillHorizontalChar*(CellWidth - 1), end='')
41+
if i == ColCount:
42+
print(CornerChar)
43+
44+
i += 1
45+
46+
def PrintGridVerticalBorders(FillVerticalChar, CellWidth, CellHeight, ColCount):
47+
j = 2 #Initialize counter for beginning 2nd row of cell fill
48+
while j <= CellHeight:
49+
#repeat CellHeight times
50+
i = 1
51+
while i <= ColCount:
52+
print(FillVerticalChar + ' '*(CellWidth - 1), end='')
53+
if i == ColCount:
54+
print(FillVerticalChar)
55+
56+
i += 1
57+
#end repeat
58+
j += 1
59+
#end j
60+
61+
def PrintGrid(CornerChar, FillHorizontalChar, FillVerticalChar, CellWidth, CellHeight, ColCount, RowCount):
62+
print('CornerChar: ' + CornerChar)
63+
print('FillHorizontalChar: ' + FillHorizontalChar)
64+
print('FillVerticalChar: ' + FillVerticalChar)
65+
print('CellWidth: ' + str(CellWidth))
66+
print('CellHeight: ' + str(CellHeight))
67+
print('ColCount: ' + str(ColCount))
68+
print('RowCount: ' + str(RowCount))
69+
70+
i = 1
71+
while i <= RowCount:
72+
PrintGridHorizontalBorder(CornerChar, FillHorizontalChar, CellWidth, ColCount)
73+
PrintGridVerticalBorders(FillVerticalChar, CellWidth, CellHeight, ColCount)
74+
75+
if i == RowCount:
76+
PrintGridHorizontalBorder(CornerChar, FillHorizontalChar, CellWidth, ColCount)
77+
78+
i += 1
79+
80+
PrintGrid('+', '-', '|', 5, 5, 2, 2)
81+
PrintGrid('+', '-', '|', 5, 5, 3, 3)
82+
PrintGrid('+', '-', '|', 10, 10, 4, 4)
83+
84+
def PrintGridInter():
85+
'''
86+
PrintGridInter: Interactive form of PrintGrid().
87+
Prompts user for arguments:
88+
CornerChar, FillHorizontalChar, FillVerticalChar,
89+
CellWidth, CellHeight, ColCount, RowCount
90+
'''
91+
92+
CornerChar = input('Type the character to use for corners...')
93+
FillHorizontalChar = input('Type the character to use for horizontal fills...')
94+
FillVerticalChar = input('Type the character to use for vertical fills...')
95+
CellWidth = int(input('How wide do you want the cells to be...'))
96+
CellHeight = int(input('How high do you want the cells to be...'))
97+
ColCount = int(input('How many columns do you want the grid to have...'))
98+
RowCount = int(input('How many rows do you want the grid to have...'))
99+
100+
i = 1
101+
while i <= RowCount:
102+
PrintGridHorizontalBorder(CornerChar, FillHorizontalChar, CellWidth, ColCount)
103+
PrintGridVerticalBorders(FillVerticalChar, CellWidth, CellHeight, ColCount)
104+
105+
if i == RowCount:
106+
PrintGridHorizontalBorder(CornerChar, FillHorizontalChar, CellWidth, ColCount)
107+
108+
i += 1
109+
110+
PrintGridInter()
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
"""This module contains a code example related to
2+
3+
Think Python, 2nd Edition
4+
by Allen Downey
5+
http://thinkpython2.com
6+
7+
Copyright 2015 Allen Downey
8+
9+
License: http://creativecommons.org/licenses/by/4.0/
10+
"""
11+
12+
from __future__ import print_function, division
13+
14+
15+
def read_dictionary(filename='c06d'):
16+
"""Reads from a file and builds a dictionary that maps from
17+
each word to a string that describes its primary pronunciation.
18+
19+
Secondary pronunciations are added to the dictionary with
20+
a number, in parentheses, at the end of the key, so the
21+
key for the second pronunciation of "abdominal" is "abdominal(2)".
22+
23+
filename: string
24+
returns: map from string to pronunciation
25+
"""
26+
d = dict()
27+
fin = open(filename)
28+
for line in fin:
29+
30+
# skip over the comments
31+
if line[0] == '#': continue
32+
33+
t = line.split()
34+
word = t[0].lower()
35+
pron = ' '.join(t[1:])
36+
d[word] = pron
37+
38+
return d
39+
40+
41+
if __name__ == '__main__':
42+
d = read_dictionary()
43+
for k, v in d.items():
44+
print(k, v)
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
"""This module contains a code example related to
2+
3+
Think Python, 2nd Edition
4+
by Allen Downey
5+
http://thinkpython2.com
6+
7+
Copyright 2015 Allen Downey
8+
9+
License: http://creativecommons.org/licenses/by/4.0/
10+
"""
11+
12+
from __future__ import print_function, division
13+
14+
import time
15+
16+
17+
def make_word_list1():
18+
"""Reads lines from a file and builds a list using append."""
19+
t = []
20+
fin = open('words.txt')
21+
for line in fin:
22+
word = line.strip()
23+
t.append(word)
24+
return t
25+
26+
27+
def make_word_list2():
28+
"""Reads lines from a file and builds a list using list +."""
29+
t = []
30+
fin = open('words.txt')
31+
for line in fin:
32+
word = line.strip()
33+
t = t + [word]
34+
return t
35+
36+
37+
start_time = time.time()
38+
t = make_word_list1()
39+
elapsed_time = time.time() - start_time
40+
41+
print(len(t))
42+
print(t[:10])
43+
print(elapsed_time, 'seconds')
44+
45+
start_time = time.time()
46+
t = make_word_list2()
47+
elapsed_time = time.time() - start_time
48+
49+
print(len(t))
50+
print(t[:10])
51+
print(elapsed_time, 'seconds')
52+

code/Markov.py

Lines changed: 74 additions & 56 deletions
Original file line numberDiff line numberDiff line change
@@ -11,78 +11,97 @@
1111

1212
from __future__ import print_function, division
1313

14-
1514
import sys
15+
import string
1616
import random
1717

18-
from markov import skip_gutenberg_header, shift
18+
# global variables
19+
suffix_map = {} # map from prefixes to a list of suffixes
20+
prefix = () # current tuple of words
1921

2022

21-
class Markov:
22-
"""Encapsulates the statistical summary of a text."""
23+
def process_file(filename, order=2):
24+
"""Reads a file and performs Markov analysis.
2325
24-
def __init__(self):
25-
self.suffix_map = {} # map from prefixes to a list of suffixes
26-
self.prefix = () # current tuple of words
26+
filename: string
27+
order: integer number of words in the prefix
2728
28-
def process_file(self, filename, order=2):
29-
"""Reads a file and performs Markov analysis.
29+
returns: map from prefix to list of possible suffixes.
30+
"""
31+
fp = open(filename)
32+
skip_gutenberg_header(fp)
3033

31-
filename: string
32-
order: integer number of words in the prefix
34+
for line in fp:
35+
for word in line.rstrip().split():
36+
process_word(word, order)
3337

34-
Returns: map from prefix to list of possible suffixes.
35-
"""
36-
fp = open(filename)
37-
skip_gutenberg_header(fp)
3838

39-
for line in fp:
40-
for word in line.rstrip().split():
41-
self.process_word(word, order)
39+
def skip_gutenberg_header(fp):
40+
"""Reads from fp until it finds the line that ends the header.
4241
43-
def process_word(self, word, order=2):
44-
"""Processes each word.
42+
fp: open file object
43+
"""
44+
for line in fp:
45+
if line.startswith('*END*THE SMALL PRINT!'):
46+
break
4547

46-
word: string
47-
order: integer
4848

49-
During the first few iterations, all we do is store up the words;
50-
after that we start adding entries to the dictionary.
51-
"""
52-
if len(self.prefix) < order:
53-
self.prefix += (word,)
54-
return
49+
def process_word(word, order=2):
50+
"""Processes each word.
51+
52+
word: string
53+
order: integer
5554
56-
try:
57-
self.suffix_map[self.prefix].append(word)
58-
except KeyError:
59-
# if there is no entry for this prefix, make one
60-
self.suffix_map[self.prefix] = [word]
55+
During the first few iterations, all we do is store up the words;
56+
after that we start adding entries to the dictionary.
57+
"""
58+
global prefix
59+
if len(prefix) < order:
60+
prefix += (word,)
61+
return
6162

62-
self.prefix = shift(self.prefix, word)
63+
try:
64+
suffix_map[prefix].append(word)
65+
except KeyError:
66+
# if there is no entry for this prefix, make one
67+
suffix_map[prefix] = [word]
68+
69+
prefix = shift(prefix, word)
70+
71+
72+
def random_text(n=100):
73+
"""Generates random wordsfrom the analyzed text.
74+
75+
Starts with a random prefix from the dictionary.
76+
77+
n: number of words to generate
78+
"""
79+
# choose a random prefix (not weighted by frequency)
80+
start = random.choice(list(suffix_map.keys()))
81+
82+
for i in range(n):
83+
suffixes = suffix_map.get(start, None)
84+
if suffixes == None:
85+
# if the start isn't in map, we got to the end of the
86+
# original text, so we have to start again.
87+
random_text(n-i)
88+
return
6389

64-
def random_text(self, n=100):
65-
"""Generates random wordsfrom the analyzed text.
90+
# choose a random suffix
91+
word = random.choice(suffixes)
92+
print(word, end=' ')
93+
start = shift(start, word)
6694

67-
Starts with a random prefix from the dictionary.
6895

69-
n: number of words to generate
70-
"""
71-
# choose a random prefix (not weighted by frequency)
72-
start = random.choice(list(self.suffix_map.keys()))
96+
def shift(t, word):
97+
"""Forms a new tuple by removing the head and adding word to the tail.
7398
74-
for i in range(n):
75-
suffixes = self.suffix_map.get(start, None)
76-
if suffixes == None:
77-
# if the prefix isn't in map, we got to the end of the
78-
# original text, so we have to start again.
79-
self.random_text(n-i)
80-
return
99+
t: tuple of strings
100+
word: string
81101
82-
# choose a random suffix
83-
word = random.choice(suffixes)
84-
print(word, end=' ')
85-
start = shift(start, word)
102+
Returns: tuple of strings
103+
"""
104+
return t[1:] + (word,)
86105

87106

88107
def main(script, filename='emma.txt', n=100, order=2):
@@ -92,11 +111,10 @@ def main(script, filename='emma.txt', n=100, order=2):
92111
except ValueError:
93112
print('Usage: %d filename [# of words] [prefix length]' % script)
94113
else:
95-
markov = Markov()
96-
markov.process_file(filename, order)
97-
markov.random_text(n)
114+
process_file(filename, order)
115+
random_text(n)
116+
print()
98117

99118

100119
if __name__ == '__main__':
101120
main(*sys.argv)
102-

code/TP_PnoJai.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
def sumall(*args):
2+
accum = 0
3+
for i in args:
4+
accum += i
5+
return accum
6+
7+
# print(sumall(1,2,3))

0 commit comments

Comments
 (0)