Skip to content

Commit 4449f0b

Browse files
authored
Merge pull request #37 from cclauss/modernize-python2-code
Modernize Python 2 code to get ready for Python 3
2 parents 32af063 + 18d25aa commit 4449f0b

File tree

42 files changed

+169
-112
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

42 files changed

+169
-112
lines changed

01-good-old-times/tf-01.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
#!/usr/bin/env python
22

3+
from __future__ import print_function
34
import sys, os, string
45

56
# Utility for handling the intermediate 'secondary memory'
@@ -121,6 +122,6 @@ def touchopen(filename, *args, **kwargs):
121122

122123
for tf in data[0:25]: # elimination of symbol tf is exercise
123124
if len(tf) == 2:
124-
print (tf[0], ' - ', tf[1])
125+
print(tf[0], ' - ', tf[1])
125126
# We're done
126127
word_freqs.close()

02-go-forth/forth.py

Lines changed: 17 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,16 @@
11
#!/usr/local/bin/python
22
#
33
# f o r t h . p y
4-
# Author: Chris Meyers @
4+
# Author: Chris Meyers @
55
# http://openbookproject.net/py4fun/forth/forth.html
66
#
7-
import sys, re
7+
from __future__ import print_function
8+
import re
9+
10+
try:
11+
raw_input # Python 2
12+
except NameError:
13+
raw_input = input # Python 3
814

915
ds = [] # The data stack
1016
cStack = [] # The control struct stack
@@ -15,14 +21,14 @@
1521
def main() :
1622
while 1 :
1723
pcode = compile() # compile/run from user
18-
if pcode == None : print; return
24+
if pcode == None : print(); return
1925
execute(pcode)
2026

2127
#============================== Lexical Parsing
22-
28+
2329
def getWord (prompt="... ") :
2430
global words
25-
while not words :
31+
while not words :
2632
try : lin = raw_input(prompt)+"\n"
2733
except : return None
2834
if lin[0:1] == "@" : lin = open(lin[1:-1]).read()
@@ -56,8 +62,8 @@ def rSwap(cod,p) : a=ds.pop(); b=ds.pop(); ds.append(a); ds.append(b)
5662
def rDup (cod,p) : ds.append(ds[-1])
5763
def rDrop(cod,p) : ds.pop()
5864
def rOver(cod,p) : ds.append(ds[-2])
59-
def rDump(cod,p) : print "ds = ", ds
60-
def rDot (cod,p) : print ds.pop()
65+
def rDump(cod,p) : print("ds = ", ds)
66+
def rDot (cod,p) : print(ds.pop())
6167
def rJmp (cod,p) : return cod[p]
6268
def rJnz (cod,p) : return (cod[p],p+1)[ds.pop()]
6369
def rJz (cod,p) : return (p+1,cod[p])[ds.pop()==0]
@@ -92,7 +98,7 @@ def rComa(cod,p) : # push tos into heap
9298

9399
'create': rCreate, 'does>': rDoes,
94100
}
95-
#================================= Compile time
101+
#================================= Compile time
96102

97103
def compile() :
98104
pcode = []; prompt = "Forth> "
@@ -114,12 +120,12 @@ def compile() :
114120
try : pcode.append(int(word))
115121
except :
116122
try: pcode.append(float(word))
117-
except :
123+
except :
118124
pcode[-1] = rRun # Change rPush to rRun
119125
pcode.append(word) # Assume word will be defined
120126
if not cStack : return pcode
121127
prompt = "... "
122-
128+
123129
def fatal (mesg) : raise mesg
124130

125131
def cColon (pcode) :
@@ -168,5 +174,5 @@ def cThen (pcode) :
168174
':' : cColon, ';' : cSemi, 'if': cIf, 'else': cElse, 'then': cThen,
169175
'begin': cBegin, 'until': cUntil,
170176
}
171-
177+
172178
if __name__ == "__main__" : main()

02-go-forth/tf-02.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
#!/usr/bin/env python
2+
from __future__ import print_function
23
import sys, re, operator, string
34

45
#
@@ -104,7 +105,7 @@ def sort():
104105
# the last word there will be one item left
105106
while stack[-1] < 25 and len(stack) > 1:
106107
heap['i'] = stack.pop()
107-
(w, f) = stack.pop(); print w, ' - ', f
108+
(w, f) = stack.pop(); print(w, ' - ', f)
108109
stack.append(heap['i']); stack.append(1)
109110
stack.append(stack.pop() + stack.pop())
110111

03-monolith/tf-03.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
#!/usr/bin/env python
22

3+
from __future__ import print_function
34
import sys, string
45
# the global list of [word, frequency] pairs
56
word_freqs = []
@@ -46,5 +47,5 @@
4647
i += 1
4748

4849
for tf in word_freqs[0:25]:
49-
print tf[0], ' - ', tf[1]
50+
print(tf[0], ' - ', tf[1])
5051

04-cookbook/tf-04.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
#!/usr/bin/env python
2+
from __future__ import print_function
23
import sys, string
34

45
# The shared mutable data
@@ -54,7 +55,7 @@ def remove_stop_words():
5455
def frequencies():
5556
"""
5657
Creates a list of pairs associating
57-
words with frequencies
58+
words with frequencies
5859
"""
5960
global words
6061
global word_freqs
@@ -70,7 +71,7 @@ def sort():
7071
Sorts word_freqs by frequency
7172
"""
7273
global word_freqs
73-
word_freqs.sort(lambda x, y: cmp(y[1], x[1]))
74+
word_freqs.sort(key=lambda x: x[1], reverse=True)
7475

7576

7677
#
@@ -84,5 +85,4 @@ def sort():
8485
sort()
8586

8687
for tf in word_freqs[0:25]:
87-
print tf[0], ' - ', tf[1]
88-
88+
print(tf[0], ' - ', tf[1])

05-pipeline/tf-05.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
#!/usr/bin/env python
2+
from __future__ import print_function
23
import sys, re, operator, string
34

45
#
@@ -65,7 +66,7 @@ def print_all(word_freqs):
6566
Takes a list of pairs where the entries are sorted by frequency and print them recursively.
6667
"""
6768
if(len(word_freqs) > 0):
68-
print word_freqs[0][0], ' - ', word_freqs[0][1]
69+
print(word_freqs[0][0], ' - ', word_freqs[0][1])
6970
print_all(word_freqs[1:]);
7071

7172
#

06-code-golf/tf-06-1.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
11
#!/usr/bin/env python
2+
from __future__ import print_function
23
import re, string, sys
34

45
stops = set(open("../stop_words.txt").read().split(",") + list(string.ascii_lowercase))
56
words = [x.lower() for x in re.split("[^a-zA-Z]+", open(sys.argv[1]).read()) if len(x) > 0 and x.lower() not in stops]
67
unique_words = list(set(words))
7-
unique_words.sort(lambda x, y: cmp(words.count(y), words.count(x)))
8-
print "\n".join(["%s - %s" % (x, words.count(x)) for x in unique_words[:25]])
8+
unique_words.sort(key=lambda x: words.count(x), reverse=True)
9+
print("\n".join(["%s - %s" % (x, words.count(x)) for x in unique_words[:25]]))

06-code-golf/tf-06-bm.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,3 @@
1+
from __future__ import print_function
2+
from functools import reduce
13
print (reduce(lambda string, tup: string + tup[0] + ' - ' + str(tup[1]) + '\n', sorted( filter(lambda tup: tup[0] not in open(__import__('os').path.join(__import__('os').path.dirname(__file__), '..', 'stop_words.txt')).read().lower().split(','), reduce(lambda word_dict, word: word_dict if (word_dict.__setitem__(word, word_dict.get(word, 0) + 1) if True else None) else word_dict, filter(lambda word: len(word) > 1, (''.join(map(lambda letter: ' ' if ord(letter) not in set(range(ord('a'), ord('z') + 1)) else letter, open(__import__('sys').argv[1]).read().lower()))).split()), {}).iteritems()), key=lambda tup: tup[1], reverse=True)[0:25], '')) # hole in one?

06-code-golf/tf-06-pn.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,11 @@
22
# My golf score is slightly lower!
33
# Best wishes, Peter Norvig
44

5+
from __future__ import print_function
56
import re, sys, collections
67

78
stopwords = set(open('../stop_words.txt').read().split(','))
89
words = re.findall('[a-z]{2,}', open(sys.argv[1]).read().lower())
910
counts = collections.Counter(w for w in words if w not in stopwords)
1011
for (w, c) in counts.most_common(25):
11-
print w, '-', c
12+
print(w, '-', c)

06-code-golf/tf-06.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
#!/usr/bin/env python
2+
from __future__ import print_function
23
import heapq, re, sys
34

45
words = re.findall("[a-z]{2,}", open(sys.argv[1]).read().lower())
56
for w in heapq.nlargest(25, set(words) - set(open("../stop_words.txt").read().split(",")), words.count):
6-
print w, "-", words.count(w)
7+
print(w, "-", words.count(w))

0 commit comments

Comments
 (0)