mirror of
https://github.com/autistic-symposium/master-algorithms-py.git
synced 2025-05-02 06:46:18 -04:00
reorganize dir
Signed-off-by: Mia Steinkirch <mia.steinkirch@gmail.com>
This commit is contained in:
parent
1b6f705e7c
commit
a8e71c50db
276 changed files with 23954 additions and 0 deletions
31
ebook_src/USEFUL/basic_examples/example_OrderedDict.py
Normal file
31
ebook_src/USEFUL/basic_examples/example_OrderedDict.py
Normal 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()
|
||||
|
||||
|
17
ebook_src/USEFUL/basic_examples/example_args.py
Executable file
17
ebook_src/USEFUL/basic_examples/example_args.py
Executable 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)
|
|
@ -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)
|
||||
|
37
ebook_src/USEFUL/basic_examples/example_comp_lists.py
Normal file
37
ebook_src/USEFUL/basic_examples/example_comp_lists.py
Normal 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)
|
32
ebook_src/USEFUL/basic_examples/example_counter.py
Normal file
32
ebook_src/USEFUL/basic_examples/example_counter.py
Normal 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()
|
||||
|
||||
|
42
ebook_src/USEFUL/basic_examples/example_decorators.py
Executable file
42
ebook_src/USEFUL/basic_examples/example_decorators.py
Executable 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)
|
27
ebook_src/USEFUL/basic_examples/example_defaultdict.py
Normal file
27
ebook_src/USEFUL/basic_examples/example_defaultdict.py
Normal 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()
|
||||
|
||||
|
15
ebook_src/USEFUL/basic_examples/example_doctest.py
Normal file
15
ebook_src/USEFUL/basic_examples/example_doctest.py
Normal 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()
|
45
ebook_src/USEFUL/basic_examples/example_fractions.py
Normal file
45
ebook_src/USEFUL/basic_examples/example_fractions.py
Normal 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()
|
||||
|
||||
|
27
ebook_src/USEFUL/basic_examples/example_generator.py
Normal file
27
ebook_src/USEFUL/basic_examples/example_generator.py
Normal 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()
|
7
ebook_src/USEFUL/basic_examples/example_lambda.py
Normal file
7
ebook_src/USEFUL/basic_examples/example_lambda.py
Normal file
|
@ -0,0 +1,7 @@
|
|||
#!/usr/bin/env python
|
||||
|
||||
__author__ = "bt3"
|
||||
|
||||
|
||||
test = lambda x: x**2
|
||||
print test(3)
|
21
ebook_src/USEFUL/basic_examples/example_logging.py
Normal file
21
ebook_src/USEFUL/basic_examples/example_logging.py
Normal 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
|
60
ebook_src/USEFUL/basic_examples/example_numpy.py
Normal file
60
ebook_src/USEFUL/basic_examples/example_numpy.py
Normal 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
|
||||
'''
|
10
ebook_src/USEFUL/basic_examples/example_open_files.py
Normal file
10
ebook_src/USEFUL/basic_examples/example_open_files.py
Normal 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
|
||||
|
58
ebook_src/USEFUL/basic_examples/example_pickle.py
Normal file
58
ebook_src/USEFUL/basic_examples/example_pickle.py
Normal 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()
|
13
ebook_src/USEFUL/basic_examples/example_queue.py
Executable file
13
ebook_src/USEFUL/basic_examples/example_queue.py
Executable 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)
|
27
ebook_src/USEFUL/basic_examples/example_random.py
Normal file
27
ebook_src/USEFUL/basic_examples/example_random.py
Normal 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()
|
||||
|
38
ebook_src/USEFUL/basic_examples/example_setdefault.py
Normal file
38
ebook_src/USEFUL/basic_examples/example_setdefault.py
Normal 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()
|
||||
|
37
ebook_src/USEFUL/basic_examples/example_sets.py
Normal file
37
ebook_src/USEFUL/basic_examples/example_sets.py
Normal 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()
|
||||
|
||||
|
||||
|
||||
|
35
ebook_src/USEFUL/basic_examples/example_socket.py
Normal file
35
ebook_src/USEFUL/basic_examples/example_socket.py
Normal 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
|
11
ebook_src/USEFUL/basic_examples/example_string_format.py
Normal file
11
ebook_src/USEFUL/basic_examples/example_string_format.py
Normal 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
|
8
ebook_src/USEFUL/basic_examples/example_subprocess.py
Normal file
8
ebook_src/USEFUL/basic_examples/example_subprocess.py
Normal file
|
@ -0,0 +1,8 @@
|
|||
#!/usr/bin/env python
|
||||
|
||||
__author__ = "bt3"
|
||||
|
||||
import subprocess,os
|
||||
|
||||
os.system('ls')
|
||||
subprocess.call(['ls', '-1'], shell=True)
|
22
ebook_src/USEFUL/basic_examples/example_telnet.py
Normal file
22
ebook_src/USEFUL/basic_examples/example_telnet.py
Normal 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')
|
46
ebook_src/USEFUL/basic_examples/example_testing.py
Normal file
46
ebook_src/USEFUL/basic_examples/example_testing.py
Normal 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
|
||||
|
16
ebook_src/USEFUL/basic_examples/example_threads.py
Normal file
16
ebook_src/USEFUL/basic_examples/example_threads.py
Normal 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()
|
24
ebook_src/USEFUL/basic_examples/example_time.py
Normal file
24
ebook_src/USEFUL/basic_examples/example_time.py
Normal 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))
|
||||
|
Loading…
Add table
Add a link
Reference in a new issue