add boilerplate for second edition

This commit is contained in:
Mia von Steinkirch 2020-02-08 17:20:00 -08:00
parent dc3ebf3173
commit 5fafebba15
279 changed files with 24265 additions and 0 deletions

View file

@ -0,0 +1,31 @@
#!/usr/bin/env python
__author__ = "bt3"
from collections import OrderedDict
def OrderedDict_example():
''' show some examples for OrderedDict '''
''' keep the order of insertion.
maintains a doubly linked list, so size is more than twice than normal dict'''
pairs = [('a', 1), ('b',2), ('c',3)]
d1 = {}
for key, value in pairs:
if key not in d1:
d1[key] = []
d1[key].append(value)
for key in d1:
print(key, d1[key])
d2 = OrderedDict(pairs)
for key in d2:
print(key, d2[key])
if __name__ == '__main__':
OrderedDict_example()

View file

@ -0,0 +1,17 @@
#!/usr/bin/env python
__author__ = "bt3"
def simple2(a, *args):
print args
def simple(*args):
print args
def simple3(**kwargs):
print kwargs
simple(1, 2, 3)
simple2(1, 2, 3)
simple3(x=1, y=2)

View file

@ -0,0 +1,28 @@
#!/usr/bin/env python
__author__ = "bt3"
import random
def benchmark(func):
import time
def wrapper(*args, **kwargs):
t = time.clock()
res = func(*args, **kwargs)
print("\t%s" % func.__name__, time.clock()-t)
return res
return wrapper
@benchmark
def random_tree(n):
temp = [n for n in range(n)]
for i in range(n+1):
temp[random.choice(temp)] = random.choice(temp)
return temp
if __name__ == '__main__':
random_tree(10000)

View file

@ -0,0 +1,62 @@
#!/usr/bin/python3
# mari von steinkirch @2013
# steinkirch at gmail
import math
class Point(object):
def __init__(self, x=0, y=0): # self: object reference to the object itself
self.x = x # data attribute
self.y = y
def distance_from_origin(self):
return math.hypot(self.x, self.y)
def __eq__(self, other):
return self.x == other.x and self.y == other.y
def __repr__(self):
return "point ({0.x!r}, {0.y!r})".format(self)
def __str__(self): # cannot be passed to eval
return "({0.x!r}, {0.y!r})".format(self)
class Circle(Point):
def __init__(self, radius, x=0, y=0):
super().__init__(x,y) # creates and initializes self.x and self.y
self.radius = radius
def edge_distance_from_origin(self):
return abs(self.distance_from_origin() - self.radius)
def area(self):
return math.pi*(self.radius**2)
def circumference(self):
return 2*math.pi*self.radius
def __eq__(self, other): # let us avoid infinite recursion
return self.radius == other.radius and super().__eq__(other)
def __repr__(self):
return "circle ({0.radius!r}, {0.x!r})".format(self)
def __str__(self):
return repr(self)
if __name__ == '__main__':
a = Point(3,4)
print(a.distance_from_origin())
c = Circle(3,2,1)
print(c)
print(c.circumference())
print(c. edge_distance_from_origin())

View file

@ -0,0 +1,37 @@
#!/usr/bin/env python
__author__ = "bt3"
a = [3, 4, 5, 6, 7]
# Filter elements greater than 4
# Bad:
b = []
for i in a:
if i > 4:
b.append(i)
print b
# Good:
print [i for i in a if i > 4]
# Or:
print filter(lambda x: x > 4, a)
# Add three to all list members:
# Bad
b = []
for i in range(len(a)):
b.append(a[i] + 3)
print b
# Good:
print [i + 3 for i in a]
# Or:
print map(lambda i: i + 3, a)

View file

@ -0,0 +1,32 @@
#!/usr/bin/env python
__author__ = "bt3"
from collections import Counter
def Counter_example():
''' it is a dictionary that maps the items to the number of occurrences '''
seq1 = [1, 2, 3, 5, 1, 2, 5, 5, 2, 5, 1, 4]
seq_counts = Counter(seq1)
print(seq_counts)
''' we can increment manually or use the update() method '''
seq2 = [1, 2, 3]
seq_counts.update(seq2)
print(seq_counts)
seq3 = [1, 4, 3]
for key in seq3:
seq_counts[key] += 1
print(seq_counts)
''' also, we can use set operations such as a-b or a+b '''
seq_counts_2 = Counter(seq3)
print(seq_counts_2)
print(seq_counts + seq_counts_2)
print(seq_counts - seq_counts_2)
if __name__ == '__main__':
Counter_example()

View file

@ -0,0 +1,19 @@
#!/bin/python
#
# An example of Python Decorator
#
def pretty_sumab(func):
def inner(a,b):
print(str(a) + " + " + str(b) + " is ", end="")
return func(a,b)
return inner
@pretty_sumab
def sumab(a,b):
summed = a + b
print(summed)
if __name__ == "__main__":
sumab(5,3)

View file

@ -0,0 +1,42 @@
#!/usr/bin/env python
__author__ = "bt3"
def logger(func):
def inner(*args): #1
print "Arguments were: {0}".format(args)
return func(*args)
return inner
@logger
def foo(x, y):
return x+y
print foo(1, 2)
def sum(func):
s = 0
for i in func():
s += i
return s
@sum
def interate():
a = []
for i in range(10):
a.append(i)
return a
print interate
# which is the same as
def interate():
a = []
for i in range(10):
a.append(i)
return a
print sum(interate)

View file

@ -0,0 +1,27 @@
#!/usr/bin/env python
__author__ = "bt3"
from collections import defaultdict
def defaultdict_example():
''' show some examples for defaultdicts '''
pairs = {('a', 1), ('b',2), ('c',3)}
d1 = {}
for key, value in pairs:
if key not in d1:
d1[key] = []
d1[key].append(value)
print(d1)
d2 = defaultdict(list)
for key, value in pairs:
d2[key].append(value)
print(d2)
if __name__ == '__main__':
defaultdict_example()

View file

@ -0,0 +1,15 @@
#!/usr/bin/python
__author__ = "bt3"
'''
The doctest module automatically runs any statement beginning with >>>
and compares the following line with the output from the interpreter.
>>> 1 == 1
False
'''
if __name__ == '__main__':
import doctest
doctest.testmod()

View file

@ -0,0 +1,45 @@
#!/usr/bin/env python
__author__ = "bt3"
from fractions import Fraction
def rounding_floats(number1, places):
return round(number1, places)
def float_to_fractions(number):
return Fraction(*number.as_integer_ratio())
def get_denominator(number1, number2):
a = Fraction(number1, number2)
return a.denominator
def get_numerator(number1, number2):
a = Fraction(number1, number2)
return a.numerator
def test_testing_floats(module_name='this module'):
number1 = 1.25
number2 = 1
number3 = -1
number4 = 5/4
number6 = 6
assert(rounding_floats(number1, number2) == 1.2)
assert(rounding_floats(number1*10, number3) == 10)
assert(float_to_fractions(number1) == number4)
assert(get_denominator(number2, number6) == number6)
assert(get_numerator(number2, number6) == number2)
s = 'Tests in {name} have {con}!'
print(s.format(name=module_name, con='passed'))
if __name__ == '__main__':
test_testing_floats()

View file

@ -0,0 +1,27 @@
#!/usr/bin/env python
__author__ = "bt3"
def interate(x):
for i in range(x):
yield i
def gen1():
a = interate(10)
print a.next()
print a.next()
print a.next()
def reverse(data):
for i in range(len(data)-1, -1, -1):
yield data[i]
def gen2():
for c in reverse('awesome'):
print c
if __name__ == '__main__':
gen1()
gen2()

View file

@ -0,0 +1,7 @@
#!/usr/bin/env python
__author__ = "bt3"
test = lambda x: x**2
print test(3)

View file

@ -0,0 +1,21 @@
#!/usr/bin/env python
__author__ = "bt3"
import logging
LOG_FILENAME = 'logging_example.out'
logging.basicConfig(filename=LOG_FILENAME,
level=logging.DEBUG,
)
logging.debug('This message should go to the log file')
f = open(LOG_FILENAME, 'rt')
try:
body = f.read()
finally:
f.close()
print 'FILE:'
print body

View file

@ -0,0 +1,18 @@
#!/usr/bin/env python3
__author__ = "bt3"
from functools import lru_cache
@lru_cache(maxsize=20)
def fib(n):
if n < 2:
return n
return fib(n-1) + fib(n-2)
if __name__ == '__main__':
print([fib(n) for n in range(10)])
print(fib.cache_info())

View file

@ -0,0 +1,60 @@
#!/usr/bin/env python
__author__ = "bt3"
import time
import numpy as np
def testing_numpy():
''' tests many features of numpy '''
ax = np.array([1,2,3])
ay = np.array([3,4,5])
print(ax)
print(ax*2)
print(ax+10)
print(np.sqrt(ax))
print(np.cos(ax))
print(ax-ay)
print(np.where(ax<2, ax, 10))
m = np.matrix([ax, ay, ax])
print(m)
print(m.T)
grid1 = np.zeros(shape=(10,10), dtype=float)
grid2 = np.ones(shape=(10,10), dtype=float)
print(grid1)
print(grid2)
print(grid1[1]+10)
print(grid2[:,2]*2)
def trad_version():
t1 = time.time()
X = range(10000000)
Y = range(10000000)
Z = []
for i in range(len(X)):
Z.append(X[i] + Y[i])
return time.time() - t1
def numpy_version():
t1 = time.time()
X = np.arange(10000000)
Y = np.arange(10000000)
Z = X + Y
return time.time() - t1
if __name__ == '__main__':
testing_numpy()
print(trad_version())
print(numpy_version())
'''
3.23564291
0.0714290142059
'''

View file

@ -0,0 +1,10 @@
#!/usr/bin/env python
__author__ = "bt3"
filename = raw_input('Enter a file name: ')
try:
f = open(filename, "r")
except:
print 'There is no file named', filename

View file

@ -0,0 +1,58 @@
#!/usr/bin/env python
__author__ = "bt3"
import pickle
def import_pickle(filename):
fh = None
try:
fh = open(filename, "rb")
mydict2 = pickle.load(fh)
return mydict2
except (EnvironmentError) as err:
print ("{0}: import error: {0}".format(os.path.basename(sys.arg[0]), err))
return false
finally:
if fh is not None:
fh.close()
def test_import_pickle():
pkl_file = 'test.dat'
mydict = import_pickle(pkl_file)
print(mydict)
def export_pickle(data, filename='test.dat', compress=False):
fh = None
try:
if compress:
fh = gzip.open(filename, "wb") # write binary
else:
fh = open(filename, "wb") # compact binary pickle format
pickle.dump(data, fh, pickle.HIGHEST_PROTOCOL)
except(EnvironmentError, pickle.PickingError) as err:
print("{0}: export error: {1}".format(os.path.basename(sys.argv[0], err)))
return False
finally:
if fh is not None:
fh.close()
def test_export_pickle():
mydict = {'a': 1, 'b': 2, 'c': 3}
export_pickle(mydict)
if __name__ == '__main__':
test_export_pickle()
test_import_pickle()

View file

@ -0,0 +1,13 @@
#!/usr/bin/env python
__author__ = "bt3"
import Queue
q = Queue.Queue()
for i in range(10):
q.put(i)
for i in range(10):
print q.get(i)

View file

@ -0,0 +1,27 @@
#!/usr/bin/env python
__author__ = "bt3"
import random
def testing_random():
''' testing the module random'''
values = [1, 2, 3, 4]
print(random.choice(values))
print(random.choice(values))
print(random.choice(values))
print(random.sample(values, 2))
print(random.sample(values, 3))
''' shuffle in place '''
random.shuffle(values)
print(values)
''' create random integers '''
print(random.randint(0,10))
print(random.randint(0,10))
if __name__ == '__main__':
testing_random()

View file

@ -0,0 +1,38 @@
#!/usr/bin/env python
__author__ = "bt3"
def usual_dict(dict_data):
newdata = {}
for k, v in dict_data:
if k in newdata:
newdata[k].append(v)
else:
newdata[k] = [v]
return newdata
def setdefault_dict(dict_data):
newdata = {}
for k, v in dict_data:
newdata.setdefault(k, []).append(v)
return newdata
def test_setdef(module_name='this module'):
dict_data = (('key1', 'value1'),
('key1', 'value2'),
('key2', 'value3'),
('key2', 'value4'),
('key2', 'value5'),)
print(usual_dict(dict_data))
print(setdefault_dict(dict_data))
s = 'Tests in {name} have {con}!'
print(s.format(name=module_name, con='passed'))
if __name__ == '__main__':
test_setdef()

View file

@ -0,0 +1,37 @@
#!/usr/bin/env python
__author__ = "bt3"
def difference(l1):
""" return the list with duplicate elements removed """
return list(set(l1))
def intersection(l1, l2):
""" return the intersection of two lists """
return list(set(l1) & set(l2))
def union(l1, l2):
""" return the union of two lists """
return list(set(l1) | set(l2))
def test_sets_operations_with_lists():
l1 = [1,2,3,4,5,9,11,15]
l2 = [4,5,6,7,8]
l3 = []
assert(difference(l1) == [1, 2, 3, 4, 5, 9, 11, 15])
assert(difference(l2) == [8, 4, 5, 6, 7])
assert(intersection(l1, l2) == [4,5])
assert(union(l1, l2) == [1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 15])
assert(difference(l3) == [])
assert(intersection(l3, l2) == l3)
assert(sorted(union(l3, l2)) == sorted(l2))
print('Tests passed!')
if __name__ == '__main__':
test_sets_operations_with_lists()

View file

@ -0,0 +1,35 @@
#!/usr/bin/env python
__author__ = "bt3"
import socket
def netcat(hostname, port, content):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((hostname, port))
s.sendall(content)
adata = []
while 1:
data = s.recv(1024)
if data == '':
break
adata.append(data)
s.close()
return adata
if __name__ == '__main__':
PORT = 12345
HOSTNAME = '54.209.5.48'
message = netcat(HOSTNAME, PORT, 'Hello!')[1]
print message

View file

@ -0,0 +1,11 @@
#!/usr/bin/env python
__author__ = "bt3"
foo = 'foo'
bar = 'bar'
print '%s%s' % (foo, bar) # It is OK
print '{0}{1}'.format(foo, bar) # It is better
print '{foo}{bar}'.format(foo=foo, bar=bar) # It is best

View file

@ -0,0 +1,8 @@
#!/usr/bin/env python
__author__ = "bt3"
import subprocess,os
os.system('ls')
subprocess.call(['ls', '-1'], shell=True)

View file

@ -0,0 +1,22 @@
#!/usr/bin/env python
__author__ = "bt3"
from telnetlib import Telnet
# examples of telnet connections
PORT = 12345
HOST = '54.209.5.48'
# creating connection
tn = Telnet(HOST ,PORT)
# reading input
msg_in2 = tn.read_all().dec_msg()
tn.read_until(b'psifer text: ')
# writing outputs
tn.write(msg.encode() + b'\n')

View file

@ -0,0 +1,46 @@
#!/usr/bin/env python
__author__ = "bt3"
def test_doctest():
'''
>>> 1 == 1
False
'''
pass
if __name__ == '__main__':
import doctest
doctest.testmod()
#####
import unittest
class BasicsTestCase(unittest.TestCase):
def test_find_name(self):
self.assertTrue(1 == 1)
self.assertFalse(1 == 2)
if __name__ == '__main__':
unittest.main()
#####
# content of test_example.py, run with $ py.test
#
# run tests over the directory
# $ nosetest
def func(x):
return x + 1
def test_answer():
assert func(3) == 4

View file

@ -0,0 +1,16 @@
#!/usr/bin/env python
__author__ = "bt3"
import threading
def worker(num):
"""thread worker function"""
print 'Worker: %s' % num
return
threads = []
for i in range(5):
t = threading.Thread(target=worker, args=(i,))
threads.append(t)
t.start()

View file

@ -0,0 +1,24 @@
#!/usr/bin/python
__author__ = "bt3"
''' a simple example of how to time a function '''
import time
def sumOfN2(n):
start = time.time()
theSum = 0
for i in range(1,n+1):
theSum = theSum + i
end = time.time()
return theSum,end-start
if __name__ == '__main__':
n = 5
print("Sum is %d and required %10.7f seconds"%sumOfN2(n))
n = 200
print("Sum is %d and required %10.7f seconds"%sumOfN2(n))