mirror of
https://github.com/autistic-symposium/master-algorithms-py.git
synced 2025-04-30 04:36:08 -04:00
clean up
This commit is contained in:
parent
1ef64d6e17
commit
e0eb554dfd
14
First_edition_2014/README.md
Normal file
14
First_edition_2014/README.md
Normal file
@ -0,0 +1,14 @@
|
|||||||
|
## Python & Algorithms Book 1st Edition (2014, a published by Hanbit Media)
|
||||||
|
|
||||||
|
➡️ 📚[Download PDF (first edition)](https://github.com/bt3gl/Python-and-Algorithms-and-Data-Structures/blob/master/First_edition_2014/ebook_pdf/book_second_edition.pdf).
|
||||||
|
|
||||||
|
|
||||||
|
## Installation:
|
||||||
|
|
||||||
|
Install dependencies in a [virtual environment](https://coderwall.com/p/8-aeka):
|
||||||
|
|
||||||
|
```
|
||||||
|
virtualenv venv
|
||||||
|
source venv/bin/activate
|
||||||
|
pip install -r requirements.txt
|
||||||
|
```
|
BIN
First_edition_2014/ebook_pdf/book_second_edition.pdf
Normal file
BIN
First_edition_2014/ebook_pdf/book_second_edition.pdf
Normal file
Binary file not shown.
18
First_edition_2014/ebook_src/USEFUL/advanced/lru_cache.py
Normal file
18
First_edition_2014/ebook_src/USEFUL/advanced/lru_cache.py
Normal 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())
|
@ -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
First_edition_2014/ebook_src/USEFUL/basic_examples/example_args.py
Executable file
17
First_edition_2014/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)
|
||||||
|
|
@ -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)
|
@ -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
First_edition_2014/ebook_src/USEFUL/basic_examples/example_decorators.py
Executable file
42
First_edition_2014/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)
|
@ -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()
|
||||||
|
|
||||||
|
|
@ -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()
|
@ -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()
|
||||||
|
|
||||||
|
|
@ -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()
|
@ -0,0 +1,7 @@
|
|||||||
|
#!/usr/bin/env python
|
||||||
|
|
||||||
|
__author__ = "bt3"
|
||||||
|
|
||||||
|
|
||||||
|
test = lambda x: x**2
|
||||||
|
print test(3)
|
@ -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
|
@ -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
|
||||||
|
'''
|
@ -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
|
||||||
|
|
@ -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
First_edition_2014/ebook_src/USEFUL/basic_examples/example_queue.py
Executable file
13
First_edition_2014/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)
|
@ -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()
|
||||||
|
|
@ -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()
|
||||||
|
|
@ -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()
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
@ -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
|
@ -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
|
@ -0,0 +1,8 @@
|
|||||||
|
#!/usr/bin/env python
|
||||||
|
|
||||||
|
__author__ = "bt3"
|
||||||
|
|
||||||
|
import subprocess,os
|
||||||
|
|
||||||
|
os.system('ls')
|
||||||
|
subprocess.call(['ls', '-1'], shell=True)
|
@ -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')
|
@ -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
|
||||||
|
|
@ -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()
|
@ -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))
|
||||||
|
|
@ -0,0 +1,42 @@
|
|||||||
|
#!/usr/bin/python3
|
||||||
|
|
||||||
|
__author__ = "bt3"
|
||||||
|
|
||||||
|
|
||||||
|
from functools import wraps
|
||||||
|
from do_benchmark import benchmark
|
||||||
|
|
||||||
|
def memo(func):
|
||||||
|
''' an example of dynamic programming using a memoizing decorator '''
|
||||||
|
cache = {}
|
||||||
|
@wraps(func)
|
||||||
|
def wrap(*args):
|
||||||
|
if args not in cache:
|
||||||
|
cache[args] = func(*args)
|
||||||
|
return cache[args]
|
||||||
|
return wrap
|
||||||
|
|
||||||
|
@memo
|
||||||
|
def find_fibonacci_seq_rec(n):
|
||||||
|
''' implements the nth fibonacci value in a recursive exponential runtime '''
|
||||||
|
if n < 2: return n
|
||||||
|
return find_fibonacci_seq_rec(n - 1) + find_fibonacci_seq_rec(n - 2)
|
||||||
|
|
||||||
|
def test_memo():
|
||||||
|
n = 50
|
||||||
|
# find_fibonacci_seq_rec = memo(find_fibonacci_seq_rec)
|
||||||
|
# @benchmark
|
||||||
|
print(find_fibonacci_seq_rec(n))
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
test_memo()
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
@ -0,0 +1,85 @@
|
|||||||
|
#!/usr/bin/python3
|
||||||
|
|
||||||
|
__author__ = "bt3"
|
||||||
|
|
||||||
|
from itertools import combinations
|
||||||
|
from bisect import bisect
|
||||||
|
from memo import memo
|
||||||
|
from do_benchmark import benchmark
|
||||||
|
|
||||||
|
def naive_longest_inc_subseq(seq):
|
||||||
|
''' naive (exponential) solution to the longest increasing subsequence problem '''
|
||||||
|
for length in range(len(seq), 0, -1):
|
||||||
|
for sub in combinations(seq, length):
|
||||||
|
if list(sub) == sorted(sub):
|
||||||
|
return len(sub)
|
||||||
|
|
||||||
|
|
||||||
|
def longest_inc_subseq1(seq):
|
||||||
|
''' an iterative algorithm for the longest increasing subsequence problem '''
|
||||||
|
end = []
|
||||||
|
for val in seq:
|
||||||
|
idx = bisect(end, val)
|
||||||
|
if idx == len(end): end.append(val)
|
||||||
|
else: end[idx] = val
|
||||||
|
return len(end)
|
||||||
|
|
||||||
|
|
||||||
|
def longest_inc_subseq2(seq):
|
||||||
|
''' another iterative algorithm for the longest increasing subsequence problem '''
|
||||||
|
L = [1] * len(seq)
|
||||||
|
for cur, val in enumerate(seq):
|
||||||
|
for pre in range(cur):
|
||||||
|
if seq[pre] <= val:
|
||||||
|
L[cur] = max(L[cur], 1 + L[pre])
|
||||||
|
return max(L)
|
||||||
|
|
||||||
|
|
||||||
|
def memoized_longest_inc_subseq(seq):
|
||||||
|
''' a memoized recursive solution to find the longest increasing subsequence problem '''
|
||||||
|
@memo
|
||||||
|
def L(cur):
|
||||||
|
res = 1
|
||||||
|
for pre in range(cur):
|
||||||
|
if seq[pre] <= seq[cur]:
|
||||||
|
res = max(res, 1 + L(pre))
|
||||||
|
return res
|
||||||
|
return max(L(i) for i in range(len(seq)))
|
||||||
|
|
||||||
|
|
||||||
|
@benchmark
|
||||||
|
def test_naive_longest_inc_subseq():
|
||||||
|
print(naive_longest_inc_subseq(s1))
|
||||||
|
|
||||||
|
benchmark
|
||||||
|
def test_longest_inc_subseq1():
|
||||||
|
print(longest_inc_subseq1(s1))
|
||||||
|
|
||||||
|
@benchmark
|
||||||
|
def test_longest_inc_subseq2():
|
||||||
|
print(longest_inc_subseq2(s1))
|
||||||
|
|
||||||
|
@benchmark
|
||||||
|
def test_memoized_longest_inc_subseq():
|
||||||
|
print(memoized_longest_inc_subseq(s1))
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
from random import randrange
|
||||||
|
s1 = [randrange(100) for i in range(25)]
|
||||||
|
print(s1)
|
||||||
|
test_naive_longest_inc_subseq()
|
||||||
|
test_longest_inc_subseq1()
|
||||||
|
test_longest_inc_subseq2()
|
||||||
|
test_memoized_longest_inc_subseq()
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
62
First_edition_2014/ebook_src/USEFUL/oop/ShapeClass.py
Normal file
62
First_edition_2014/ebook_src/USEFUL/oop/ShapeClass.py
Normal 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())
|
||||||
|
|
||||||
|
|
||||||
|
|
0
First_edition_2014/ebook_src/USEFUL/oop/__init__.py
Normal file
0
First_edition_2014/ebook_src/USEFUL/oop/__init__.py
Normal file
@ -0,0 +1,30 @@
|
|||||||
|
#!/usr/bin/env python
|
||||||
|
|
||||||
|
|
||||||
|
__author__ = "bt3"
|
||||||
|
|
||||||
|
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
import shutil
|
||||||
|
|
||||||
|
def change_file_ext():
|
||||||
|
""" read a file and an extension from the command line and produces a copy with its extension changed"""
|
||||||
|
if len(sys.argv) < 2:
|
||||||
|
print("Usage: change_ext.py filename.old_ext 'new_ext'")
|
||||||
|
sys.exit()
|
||||||
|
|
||||||
|
name = os.path.splitext(sys.argv[1])[0] + "." + sys.argv[2]
|
||||||
|
print (name)
|
||||||
|
|
||||||
|
try:
|
||||||
|
shutil.copyfile(sys.argv[1], name)
|
||||||
|
except OSError as err:
|
||||||
|
print (err)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
change_file_ext()
|
||||||
|
|
||||||
|
|
@ -0,0 +1,28 @@
|
|||||||
|
#!/usr/bin/python
|
||||||
|
|
||||||
|
__author__ = "bt3"
|
||||||
|
|
||||||
|
|
||||||
|
import collections
|
||||||
|
import string
|
||||||
|
import sys
|
||||||
|
|
||||||
|
def count_unique_word_file():
|
||||||
|
if len(sys.argv) < 2:
|
||||||
|
print "Usage: python count_unique_word.py NAMEFILE"
|
||||||
|
|
||||||
|
words = collections.defaultdict(int)
|
||||||
|
strip = string.whitespace + string.punctuation + string.digits + "\"'"
|
||||||
|
for filename in sys.argv[1:]:
|
||||||
|
with open(filename) as file:
|
||||||
|
for line in file:
|
||||||
|
for word in line.lower().split():
|
||||||
|
word = word.strip(strip)
|
||||||
|
if len(word) > 2:
|
||||||
|
words[word] = +1
|
||||||
|
for word in sorted(words):
|
||||||
|
print("'{0}' occurs {1} times.".format(word, words[word]))
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
count_unique_word_file()
|
@ -0,0 +1,15 @@
|
|||||||
|
#!/usr/bin/python
|
||||||
|
|
||||||
|
__author__ = "bt3"
|
||||||
|
|
||||||
|
|
||||||
|
import collections
|
||||||
|
import sys
|
||||||
|
|
||||||
|
def count_unique_word_freq():
|
||||||
|
return collections.Counter(\
|
||||||
|
sys.stdin.read().lower().split()).most_common(n)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
count_unique_word_freq()
|
@ -0,0 +1,27 @@
|
|||||||
|
#!/usr/bin/env python
|
||||||
|
|
||||||
|
|
||||||
|
__author__ = "bt3"
|
||||||
|
|
||||||
|
import sys
|
||||||
|
|
||||||
|
def grep_word_from_files():
|
||||||
|
''' using iterator enumerate to create a grep command '''
|
||||||
|
word = sys.argv[1]
|
||||||
|
for filename in sys.argv[2:]:
|
||||||
|
with open(filename) as file:
|
||||||
|
for lino, line in enumerate(file, start=1):
|
||||||
|
if word in line:
|
||||||
|
print("{0}:{1}:{2:.40}".format(filename, lino, line.rstrip()))
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
if len(sys.argv) < 2:
|
||||||
|
print("Usage: grep_word_from_files.py word infile1 [infile2...]")
|
||||||
|
sys.exit()
|
||||||
|
else:
|
||||||
|
grep_word_from_files()
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
@ -0,0 +1,54 @@
|
|||||||
|
#!/usr/bin/env python
|
||||||
|
|
||||||
|
|
||||||
|
__author__ = "bt3"
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
|
||||||
|
def read_data(filename):
|
||||||
|
lines = []
|
||||||
|
fh = None
|
||||||
|
try:
|
||||||
|
fh = open(filename)
|
||||||
|
for line in fh:
|
||||||
|
if line.strip():
|
||||||
|
lines.append(line)
|
||||||
|
except (IOError, OSError) as err:
|
||||||
|
print(err)
|
||||||
|
finally:
|
||||||
|
if fh is not None:
|
||||||
|
fh.close()
|
||||||
|
return lines
|
||||||
|
|
||||||
|
|
||||||
|
def write_data(lines, filename):
|
||||||
|
fh = None
|
||||||
|
try:
|
||||||
|
fh = open(filename, "w")
|
||||||
|
for line in lines:
|
||||||
|
fh.write(line)
|
||||||
|
except (EnvironmentError) as err:
|
||||||
|
print(err)
|
||||||
|
finally:
|
||||||
|
if fh is not None:
|
||||||
|
fh.close()
|
||||||
|
|
||||||
|
|
||||||
|
def remove_blank_lines():
|
||||||
|
""" read a list of filenames on the command line and for each one produces another file with the same content but with no blank lines """
|
||||||
|
|
||||||
|
if len(sys.argv) < 2:
|
||||||
|
print ("Usage: noblank.py infile1 [infile2...]")
|
||||||
|
|
||||||
|
for filename in sys.argv[1:]:
|
||||||
|
lines = read_data(filename)
|
||||||
|
if lines:
|
||||||
|
write_data(lines, filename)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
remove_blank_lines()
|
||||||
|
|
41
First_edition_2014/ebook_src/abstract_structures/HashTable.py
Executable file
41
First_edition_2014/ebook_src/abstract_structures/HashTable.py
Executable file
@ -0,0 +1,41 @@
|
|||||||
|
#!/usr/bin/env python
|
||||||
|
|
||||||
|
__author__ = "bt3"
|
||||||
|
|
||||||
|
|
||||||
|
class HashTable(object):
|
||||||
|
def __init__(self, slots=10):
|
||||||
|
self.slots = slots
|
||||||
|
self.table = []
|
||||||
|
self.create_table()
|
||||||
|
|
||||||
|
def hash_key(self, value):
|
||||||
|
return hash(value)%self.slots
|
||||||
|
|
||||||
|
def create_table(self):
|
||||||
|
for i in range(self.slots):
|
||||||
|
self.table.append([])
|
||||||
|
|
||||||
|
def add_item(self, value):
|
||||||
|
key = self.hash_key(value)
|
||||||
|
self.table[key].append(value)
|
||||||
|
|
||||||
|
def print_table(self):
|
||||||
|
for key in range(len(self.table)):
|
||||||
|
print "Key is %s, value is %s." %(key, self.table[key])
|
||||||
|
|
||||||
|
def find_item(self, item):
|
||||||
|
pos = self.hash_key(item)
|
||||||
|
if item in self.table[pos]:
|
||||||
|
return True
|
||||||
|
else:
|
||||||
|
return False
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
dic = HashTable(5)
|
||||||
|
for i in range(1, 40, 2):
|
||||||
|
dic.add_item(i)
|
||||||
|
|
||||||
|
dic.print_table()
|
||||||
|
assert(dic.find_item(20) == False)
|
||||||
|
assert(dic.find_item(21) == True)
|
47
First_edition_2014/ebook_src/abstract_structures/Queue.py
Executable file
47
First_edition_2014/ebook_src/abstract_structures/Queue.py
Executable file
@ -0,0 +1,47 @@
|
|||||||
|
#!/usr/bin/env python
|
||||||
|
# Time: 5 min
|
||||||
|
|
||||||
|
__author__ = "bt3"
|
||||||
|
|
||||||
|
|
||||||
|
class Queue(object):
|
||||||
|
def __init__(self):
|
||||||
|
self.enq = []
|
||||||
|
self.deq = []
|
||||||
|
|
||||||
|
def enqueue(self, item):
|
||||||
|
return self.enq.append(item)
|
||||||
|
|
||||||
|
def deque(self):
|
||||||
|
if not self.deq:
|
||||||
|
while self.enq:
|
||||||
|
self.deq.append(self.enq.pop())
|
||||||
|
return self.deq.pop()
|
||||||
|
|
||||||
|
def peak(self):
|
||||||
|
if not self.deq:
|
||||||
|
while self.enq:
|
||||||
|
self.deq.append(self.enq.pop())
|
||||||
|
if self.deq:
|
||||||
|
return self.deq[-1]
|
||||||
|
|
||||||
|
def size(self):
|
||||||
|
return len(self.enq) + len(self.deq)
|
||||||
|
|
||||||
|
def isempty(self):
|
||||||
|
return not (self.enq + self.deq)
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
q = Queue()
|
||||||
|
for i in range(1,11):
|
||||||
|
q.enqueue(i)
|
||||||
|
print 'Size:', q.size()
|
||||||
|
print 'Is empty?', q.isempty()
|
||||||
|
print 'Peak: ', q.peak()
|
||||||
|
print
|
||||||
|
print 'Dequeuing...'
|
||||||
|
for i in range(10):
|
||||||
|
print q.deque()
|
||||||
|
print 'Size:', q.size()
|
||||||
|
print 'Is empty?', q.isempty()
|
||||||
|
print 'Peak: ', q.peak()
|
63
First_edition_2014/ebook_src/abstract_structures/Stack.py
Executable file
63
First_edition_2014/ebook_src/abstract_structures/Stack.py
Executable file
@ -0,0 +1,63 @@
|
|||||||
|
#!/usr/bin/env python
|
||||||
|
|
||||||
|
__author__ = "bt3"
|
||||||
|
|
||||||
|
|
||||||
|
class Stack(object):
|
||||||
|
def __init__(self):
|
||||||
|
self.content = []
|
||||||
|
self.min_array = []
|
||||||
|
self.min = float('inf')
|
||||||
|
|
||||||
|
def push(self, value):
|
||||||
|
if value < self.min:
|
||||||
|
self.min = value
|
||||||
|
|
||||||
|
self.content.append(value)
|
||||||
|
self.min_array.append(self.min)
|
||||||
|
|
||||||
|
def pop(self):
|
||||||
|
if self.content:
|
||||||
|
value = self.content.pop()
|
||||||
|
self.min_array.pop()
|
||||||
|
if self.min_array:
|
||||||
|
self.min = self.min_array[-1]
|
||||||
|
return value
|
||||||
|
else:
|
||||||
|
return 'Empty List. '
|
||||||
|
|
||||||
|
def find_min(self):
|
||||||
|
if self.min_array:
|
||||||
|
return self.min_array[-1]
|
||||||
|
else:
|
||||||
|
return 'No min value for empty list.'
|
||||||
|
|
||||||
|
def size(self):
|
||||||
|
return len(self.content)
|
||||||
|
|
||||||
|
def isEmpty(self):
|
||||||
|
return not bool(self.content)
|
||||||
|
|
||||||
|
def peek(self):
|
||||||
|
if self.content:
|
||||||
|
return self.content[-1]
|
||||||
|
else:
|
||||||
|
print('Stack is empty.')
|
||||||
|
|
||||||
|
|
||||||
|
def __repr__(self):
|
||||||
|
return '{}'.format(self.content)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
q = Stack()
|
||||||
|
|
||||||
|
for i in range(15,20):
|
||||||
|
q.push(i)
|
||||||
|
for i in range(10,5,-1):
|
||||||
|
q.push(i)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
for i in range(1, 13):
|
||||||
|
print q.pop(), q.find_min()
|
1
First_edition_2014/ebook_src/abstract_structures/__init__.py
Executable file
1
First_edition_2014/ebook_src/abstract_structures/__init__.py
Executable file
@ -0,0 +1 @@
|
|||||||
|
__all__=["hash_tables", "heap", "linked_list", "queues", "stacks"]
|
@ -0,0 +1,51 @@
|
|||||||
|
#!/usr/bin/env python
|
||||||
|
|
||||||
|
__author__ = "bt3"
|
||||||
|
|
||||||
|
import heapq
|
||||||
|
|
||||||
|
def find_N_largest_items_seq(seq, N):
|
||||||
|
''' find the N largest items in a sequence '''
|
||||||
|
return heapq.nlargest(N,seq)
|
||||||
|
|
||||||
|
def find_N_smallest_items_seq(seq, N):
|
||||||
|
''' find the N smallest items in a sequence '''
|
||||||
|
return heapq.nsmallest(N, seq)
|
||||||
|
|
||||||
|
def find_smallest_items_seq_heap(seq):
|
||||||
|
''' find the smallest items in a sequence using heapify first'''
|
||||||
|
''' heap[0] is always the smallest item '''
|
||||||
|
''' pops the smallest item, O(logN) '''
|
||||||
|
heapq.heapify(seq)
|
||||||
|
return heapq.heappop(seq)
|
||||||
|
|
||||||
|
def find_smallest_items_seq(seq):
|
||||||
|
''' if it is only one item, min() is faster '''
|
||||||
|
return min(seq)
|
||||||
|
|
||||||
|
def find_N_smallest_items_seq_sorted(seq, N):
|
||||||
|
''' N ~ len(seq), better sort instead'''
|
||||||
|
return sorted(seq)[:N]
|
||||||
|
|
||||||
|
def find_N_largest_items_seq_sorted(seq, N):
|
||||||
|
''' N ~ len(seq), better sort instead'''
|
||||||
|
return sorted(seq)[len(seq)-N:]
|
||||||
|
|
||||||
|
|
||||||
|
def test_find_N_largest_smallest_items_seq(module_name='this module'):
|
||||||
|
seq = [1, 3, 2, 8, 6, 10, 9]
|
||||||
|
N = 3
|
||||||
|
assert(find_N_largest_items_seq(seq, N) == [10, 9, 8])
|
||||||
|
assert(find_N_largest_items_seq_sorted(seq, N) == [8, 9, 10])
|
||||||
|
assert(find_N_smallest_items_seq(seq, N) == [1,2,3])
|
||||||
|
assert(find_N_smallest_items_seq_sorted(seq, N) == [1,2,3])
|
||||||
|
assert(find_smallest_items_seq(seq) == 1)
|
||||||
|
assert(find_smallest_items_seq_heap(seq) == 1)
|
||||||
|
|
||||||
|
s = 'Tests in {name} have {con}!'
|
||||||
|
print(s.format(name=module_name, con='passed'))
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
test_find_N_largest_smallest_items_seq()
|
||||||
|
|
@ -0,0 +1,49 @@
|
|||||||
|
#!/usr/bin/env python
|
||||||
|
|
||||||
|
__author__ = "bt3"
|
||||||
|
|
||||||
|
class Heapify(object):
|
||||||
|
def __init__(self, data=None):
|
||||||
|
self.data = data or []
|
||||||
|
for i in range(len(data)//2, -1, -1):
|
||||||
|
self.__max_heapify__(i)
|
||||||
|
|
||||||
|
def __repr__(self):
|
||||||
|
return '{}'.format(self.data)
|
||||||
|
|
||||||
|
def parent(self, i):
|
||||||
|
return i >> 1
|
||||||
|
|
||||||
|
def left_child(self, i):
|
||||||
|
return (i << 1) + 1
|
||||||
|
|
||||||
|
def right_child(self, i):
|
||||||
|
return (i << 1) + 2 # +2 instead of +1 because it's 0-indexed.
|
||||||
|
|
||||||
|
def __max_heapify__(self, i):
|
||||||
|
largest = i
|
||||||
|
left = self.left_child(i)
|
||||||
|
right = self.right_child(i)
|
||||||
|
n = len(self.data)
|
||||||
|
largest = (left < n and self.data[left] > self.data[i]) and left or i
|
||||||
|
largest = (right < n and self.data[right] > self.data[largest]) and right or largest
|
||||||
|
if i is not largest:
|
||||||
|
self.data[i], self.data[largest] = self.data[largest], self.data[i]
|
||||||
|
self.__max_heapify__(largest)
|
||||||
|
|
||||||
|
def extract_max(self):
|
||||||
|
n = len(self.data)
|
||||||
|
max_element = self.data[0]
|
||||||
|
self.data[0] = self.data[n - 1]
|
||||||
|
self.data = self.data[:n - 1]
|
||||||
|
self.__max_heapify__(0)
|
||||||
|
return max_element
|
||||||
|
|
||||||
|
|
||||||
|
def test_Heapify():
|
||||||
|
l1 = [3, 2, 5, 1, 7, 8, 2]
|
||||||
|
h = Heapify(l1)
|
||||||
|
assert(h.extract_max() == 8)
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
test_Heapify()
|
@ -0,0 +1,27 @@
|
|||||||
|
#!/usr/bin/env python
|
||||||
|
|
||||||
|
__author__ = "bt3"
|
||||||
|
|
||||||
|
import heapq
|
||||||
|
|
||||||
|
|
||||||
|
def merge_sorted_seq(seq1, seq2):
|
||||||
|
''' merge two sorted sequences with little ovehead. the result
|
||||||
|
will be sorted, which is different of doing just +'''
|
||||||
|
result = []
|
||||||
|
for c in heapq.merge(seq1, seq2):
|
||||||
|
result.append(c)
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
def test_merge_sorted_seq(module_name='this module'):
|
||||||
|
seq1 = [1, 2, 3, 8, 9, 10]
|
||||||
|
seq2 = [2, 3, 4, 5, 6, 7, 9]
|
||||||
|
seq3 = seq1 + seq2
|
||||||
|
assert(merge_sorted_seqseq1, seq2) == sorted(seq3))
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
test_merge_sorted_seq()
|
||||||
|
|
@ -0,0 +1,40 @@
|
|||||||
|
#!/usr/bin/env python
|
||||||
|
|
||||||
|
__author__ = "bt3"
|
||||||
|
|
||||||
|
import heapq
|
||||||
|
|
||||||
|
class PriorityQueue(object):
|
||||||
|
''' implements a priority queue class '''
|
||||||
|
def __init__(self):
|
||||||
|
self._queue = []
|
||||||
|
self._index = 0 # comparying same priority level
|
||||||
|
|
||||||
|
def push(self, item, priority):
|
||||||
|
heapq.heappush(self._queue, (-priority, self._index, item))
|
||||||
|
self._index += 1
|
||||||
|
|
||||||
|
def pop(self):
|
||||||
|
return heapq.heappop(self._queue)[-1]
|
||||||
|
|
||||||
|
|
||||||
|
class Item:
|
||||||
|
def __init__(self, name):
|
||||||
|
self.name = name
|
||||||
|
def __repr__(self):
|
||||||
|
return "Item({!r})".format(self.name)
|
||||||
|
|
||||||
|
|
||||||
|
def test_PriorityQueue():
|
||||||
|
''' push and pop are all O(logN) '''
|
||||||
|
q = PriorityQueue()
|
||||||
|
q.push(Item('test1'), 1)
|
||||||
|
q.push(Item('test2'), 4)
|
||||||
|
q.push(Item('test3'), 3)
|
||||||
|
assert(str(q.pop()) == "Item('test2')")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
test_PriorityQueue()
|
||||||
|
|
||||||
|
|
@ -0,0 +1,55 @@
|
|||||||
|
#!/usr/bin/env python
|
||||||
|
|
||||||
|
__author__ = "bt3"
|
||||||
|
|
||||||
|
|
||||||
|
''' implement a function to see whether a linked list is circular.
|
||||||
|
To implement this, we just need two pointers with different
|
||||||
|
paces (for example, one goes twice faster)'''
|
||||||
|
|
||||||
|
from linked_list_fifo import LinkedListFIFO
|
||||||
|
from node import Node
|
||||||
|
|
||||||
|
|
||||||
|
class cicularLinkedListFIFO(LinkedListFIFO):
|
||||||
|
def _add(self, value):
|
||||||
|
self.length += 1
|
||||||
|
node = Node(value, self.head)
|
||||||
|
if self.tail:
|
||||||
|
self.tail.pointer = node
|
||||||
|
self.tail = node
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
def isCircularll(ll):
|
||||||
|
p1 = ll.head
|
||||||
|
p2 = ll.head
|
||||||
|
|
||||||
|
while p2:
|
||||||
|
try:
|
||||||
|
p1 = p1.pointer
|
||||||
|
p2 = p2.pointer.pointer
|
||||||
|
except:
|
||||||
|
break
|
||||||
|
|
||||||
|
if p1 == p2:
|
||||||
|
return True
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
|
||||||
|
ll = LinkedListFIFO()
|
||||||
|
for i in range(10):
|
||||||
|
ll.addNode(i)
|
||||||
|
ll._printList()
|
||||||
|
|
||||||
|
print(isCircularll(ll))
|
||||||
|
|
||||||
|
lcirc = cicularLinkedListFIFO()
|
||||||
|
for i in range(10):
|
||||||
|
lcirc.addNode(i)
|
||||||
|
print(isCircularll(lcirc))
|
||||||
|
|
@ -0,0 +1,81 @@
|
|||||||
|
#!/usr/bin/env python
|
||||||
|
|
||||||
|
__author__ = "bt3"
|
||||||
|
|
||||||
|
''' Implement a double-linked list, which is very simple, we just need inherits
|
||||||
|
from a Linked List Class and add an attribute for previous.'''
|
||||||
|
|
||||||
|
from linked_list_fifo import LinkedListFIFO
|
||||||
|
|
||||||
|
|
||||||
|
class dNode(object):
|
||||||
|
def __init__(self, value=None, pointer=None, previous=None):
|
||||||
|
self.value = value
|
||||||
|
self.pointer = pointer
|
||||||
|
self.previous = previous
|
||||||
|
|
||||||
|
|
||||||
|
class dLinkList(LinkedListFIFO):
|
||||||
|
|
||||||
|
def printListInverse(self):
|
||||||
|
node = self.tail
|
||||||
|
while node:
|
||||||
|
print(node.value)
|
||||||
|
try:
|
||||||
|
node = node.previous
|
||||||
|
except:
|
||||||
|
break
|
||||||
|
|
||||||
|
def _add(self, value):
|
||||||
|
self.length += 1
|
||||||
|
node = dNode(value)
|
||||||
|
if self.tail:
|
||||||
|
self.tail.pointer = node
|
||||||
|
node.previous = self.tail
|
||||||
|
self.tail = node
|
||||||
|
|
||||||
|
def _delete(self, node):
|
||||||
|
self.length -= 1
|
||||||
|
node.previous.pointer = node.pointer
|
||||||
|
if not node.pointer:
|
||||||
|
self.tail = node.previous
|
||||||
|
|
||||||
|
def _find(self, index):
|
||||||
|
node = self.head
|
||||||
|
i = 0
|
||||||
|
while node and i < index:
|
||||||
|
node = node.pointer
|
||||||
|
i += 1
|
||||||
|
return node, i
|
||||||
|
|
||||||
|
# delete nodes in general
|
||||||
|
def deleteNode(self, index):
|
||||||
|
if not self.head or not self.head.pointer:
|
||||||
|
self._deleteFirst()
|
||||||
|
else:
|
||||||
|
node, i = self._find(index)
|
||||||
|
if i == index:
|
||||||
|
self._delete(node)
|
||||||
|
else:
|
||||||
|
print('Node with index {} not found'.format(index))
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
|
||||||
|
from collections import Counter
|
||||||
|
|
||||||
|
ll = dLinkList()
|
||||||
|
for i in range(1, 5):
|
||||||
|
ll.addNode(i)
|
||||||
|
print('Printing the list...')
|
||||||
|
ll._printList()
|
||||||
|
print('Now, printing the list inversely...')
|
||||||
|
ll.printListInverse()
|
||||||
|
print('The list after adding node with value 15')
|
||||||
|
ll._add(15)
|
||||||
|
ll._printList()
|
||||||
|
print("The list after deleting everything...")
|
||||||
|
for i in range(ll.length-1, -1, -1):
|
||||||
|
ll.deleteNode(i)
|
||||||
|
ll._printList()
|
||||||
|
|
@ -0,0 +1,42 @@
|
|||||||
|
#!/usr/bin/env python
|
||||||
|
|
||||||
|
__author__ = "bt3"
|
||||||
|
|
||||||
|
|
||||||
|
''' Find the mth-to-last element of a linked list.
|
||||||
|
One option is having two pointers, separated by m. P1 start at the roots
|
||||||
|
(p1 = self.root) and p2 is m-behinf pointer, which is created when p1 is at m.
|
||||||
|
When p1 reach the end, p2 is the node. '''
|
||||||
|
|
||||||
|
from linked_list_fifo import LinkedListFIFO
|
||||||
|
from node import Node
|
||||||
|
|
||||||
|
|
||||||
|
class LinkedListFIFO_find_kth(LinkedListFIFO):
|
||||||
|
|
||||||
|
|
||||||
|
def find_kth_to_last(self, k):
|
||||||
|
p1, p2 = self.head, self.head
|
||||||
|
i = 0
|
||||||
|
while p1:
|
||||||
|
if i > k:
|
||||||
|
try:
|
||||||
|
p2 = p2.pointer
|
||||||
|
except:
|
||||||
|
break
|
||||||
|
p1 = p1.pointer
|
||||||
|
i += 1
|
||||||
|
return p2.value
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
ll = LinkedListFIFO_find_kth()
|
||||||
|
for i in range(1, 11):
|
||||||
|
ll.addNode(i)
|
||||||
|
print('The Linked List:')
|
||||||
|
print(ll._printList())
|
||||||
|
k = 3
|
||||||
|
k_from_last = ll.find_kth_to_last(k)
|
||||||
|
print("The %dth element to the last of the LL of size %d is %d" %(k, ll.length, k_from_last))
|
||||||
|
|
@ -0,0 +1,90 @@
|
|||||||
|
#!/usr/bin/env python
|
||||||
|
|
||||||
|
__author__ = "bt3"
|
||||||
|
|
||||||
|
''' A class for a linked list that has the nodes in a FIFO order (such as a queue)'''
|
||||||
|
|
||||||
|
|
||||||
|
from node import Node
|
||||||
|
|
||||||
|
class LinkedListFIFO(object):
|
||||||
|
|
||||||
|
def __init__(self):
|
||||||
|
self.head = None
|
||||||
|
self.length = 0
|
||||||
|
self.tail = None # this is different from ll lifo
|
||||||
|
|
||||||
|
def _printList(self):
|
||||||
|
node = self.head
|
||||||
|
while node:
|
||||||
|
print(node.value)
|
||||||
|
node = node.pointer
|
||||||
|
|
||||||
|
def _addFirst(self, value):
|
||||||
|
self.length = 1
|
||||||
|
node = Node(value)
|
||||||
|
self.head = node
|
||||||
|
self.tail = node
|
||||||
|
|
||||||
|
def _deleteFirst(self):
|
||||||
|
self.length = 0
|
||||||
|
self.head = None
|
||||||
|
self.tail = None
|
||||||
|
print('The list is empty.')
|
||||||
|
|
||||||
|
def _add(self, value):
|
||||||
|
self.length += 1
|
||||||
|
node = Node(value)
|
||||||
|
if self.tail:
|
||||||
|
self.tail.pointer = node
|
||||||
|
self.tail = node
|
||||||
|
|
||||||
|
def addNode(self, value):
|
||||||
|
if not self.head:
|
||||||
|
self._addFirst(value)
|
||||||
|
else:
|
||||||
|
self._add(value)
|
||||||
|
|
||||||
|
def _find(self, index):
|
||||||
|
prev = None
|
||||||
|
node = self.head
|
||||||
|
i = 0
|
||||||
|
while node and i < index:
|
||||||
|
prev = node
|
||||||
|
node = node.pointer
|
||||||
|
i += 1
|
||||||
|
return node, prev, i
|
||||||
|
|
||||||
|
def deleteNode(self, index):
|
||||||
|
if not self.head or not self.head.pointer:
|
||||||
|
self._deleteFirst()
|
||||||
|
else:
|
||||||
|
node, prev, i = self._find(index)
|
||||||
|
if i == index and node:
|
||||||
|
self.length -= 1
|
||||||
|
if i == 0 or not prev :
|
||||||
|
self.head = node.pointer
|
||||||
|
else:
|
||||||
|
prev.pointer = node.pointer
|
||||||
|
if not self.tail == node:
|
||||||
|
self.tail = prev
|
||||||
|
else:
|
||||||
|
print('Node with index {} not found'.format(index))
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
ll = LinkedListFIFO()
|
||||||
|
for i in range(1, 5):
|
||||||
|
ll.addNode(i)
|
||||||
|
print('The list is:')
|
||||||
|
ll._printList()
|
||||||
|
print('The list after deleting node with index 2:')
|
||||||
|
ll.deleteNode(2)
|
||||||
|
ll._printList()
|
||||||
|
print('The list after adding node with value 15')
|
||||||
|
ll._add(15)
|
||||||
|
ll._printList()
|
||||||
|
print("The list after deleting everything...")
|
||||||
|
for i in range(ll.length-1, -1, -1):
|
||||||
|
ll.deleteNode(i)
|
||||||
|
ll._printList()
|
@ -0,0 +1,90 @@
|
|||||||
|
#!/usr/bin/env python
|
||||||
|
|
||||||
|
__author__ = "bt3"
|
||||||
|
|
||||||
|
|
||||||
|
''' Implement a unordered linked list, i.e. a LIFO linked list (like a stack) '''
|
||||||
|
|
||||||
|
from node import Node
|
||||||
|
|
||||||
|
class LinkedListLIFO(object):
|
||||||
|
|
||||||
|
def __init__(self):
|
||||||
|
self.head = None
|
||||||
|
self.length = 0
|
||||||
|
|
||||||
|
def _printList(self):
|
||||||
|
node = self.head
|
||||||
|
while node:
|
||||||
|
print(node.value)
|
||||||
|
node = node.pointer
|
||||||
|
|
||||||
|
def _delete(self, prev, node):
|
||||||
|
self.length -= 1
|
||||||
|
if not prev:
|
||||||
|
self.head = node.pointer
|
||||||
|
else:
|
||||||
|
prev.pointer = node.pointer
|
||||||
|
|
||||||
|
def _add(self, value):
|
||||||
|
self.length += 1
|
||||||
|
self.head = Node(value, self.head)
|
||||||
|
|
||||||
|
def _find(self, index):
|
||||||
|
prev = None
|
||||||
|
node = self.head
|
||||||
|
i = 0
|
||||||
|
while node and i < index:
|
||||||
|
prev = node
|
||||||
|
node = node.pointer
|
||||||
|
i += 1
|
||||||
|
return node, prev, i
|
||||||
|
|
||||||
|
def _find_by_value(self, value):
|
||||||
|
prev = None
|
||||||
|
node = self.head
|
||||||
|
found = 0
|
||||||
|
while node and not found:
|
||||||
|
if node.value == value:
|
||||||
|
found = True
|
||||||
|
else:
|
||||||
|
prev = node
|
||||||
|
node = node.pointer
|
||||||
|
return node, prev, found
|
||||||
|
|
||||||
|
def deleteNode(self, index):
|
||||||
|
node, prev, i = self._find(index)
|
||||||
|
if index == i:
|
||||||
|
self._delete(prev, node)
|
||||||
|
else:
|
||||||
|
print('Node with index {} not found'.format(index))
|
||||||
|
|
||||||
|
def deleteNodeByValue(self, value):
|
||||||
|
node, prev, found = self._find_by_value(value)
|
||||||
|
if found:
|
||||||
|
self._delete(prev, node)
|
||||||
|
else:
|
||||||
|
print('Node with value {} not found'.format(value))
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
ll = LinkedListLIFO()
|
||||||
|
for i in range(1, 5):
|
||||||
|
ll._add(i)
|
||||||
|
print('The list is:')
|
||||||
|
ll._printList()
|
||||||
|
print('The list after deleting node with index 2:')
|
||||||
|
ll.deleteNode(2)
|
||||||
|
ll._printList()
|
||||||
|
print('The list after deleting node with value 3:')
|
||||||
|
ll.deleteNodeByValue(2)
|
||||||
|
ll._printList()
|
||||||
|
print('The list after adding node with value 15')
|
||||||
|
ll._add(15)
|
||||||
|
ll._printList()
|
||||||
|
print("The list after deleting everything...")
|
||||||
|
for i in range(ll.length-1, -1, -1):
|
||||||
|
ll.deleteNode(i)
|
||||||
|
ll._printList()
|
@ -0,0 +1,33 @@
|
|||||||
|
#!/usr/bin/env python
|
||||||
|
|
||||||
|
__author__ = "bt3"
|
||||||
|
|
||||||
|
class Node(object):
|
||||||
|
def __init__(self, value=None, pointer=None):
|
||||||
|
self.value = value
|
||||||
|
self.pointer = pointer
|
||||||
|
|
||||||
|
def getData(self):
|
||||||
|
return self.value
|
||||||
|
|
||||||
|
def getNext(self):
|
||||||
|
return self.pointer
|
||||||
|
|
||||||
|
def setData(self, newdata):
|
||||||
|
self.value = newdata
|
||||||
|
|
||||||
|
def setNext(self, newpointer):
|
||||||
|
self.pointer = newpointer
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
L = Node("a", Node("b", Node("c", Node("d"))))
|
||||||
|
assert(L.pointer.pointer.value=='c')
|
||||||
|
|
||||||
|
print(L.getData())
|
||||||
|
print(L.getNext().getData())
|
||||||
|
L.setData('aa')
|
||||||
|
L.setNext(Node('e'))
|
||||||
|
print(L.getData())
|
||||||
|
print(L.getNext().getData())
|
@ -0,0 +1,57 @@
|
|||||||
|
#!/usr/bin/env python
|
||||||
|
|
||||||
|
__author__ = "bt3"
|
||||||
|
|
||||||
|
''' This function divides a linked list in a value, where everything smaller than this value
|
||||||
|
goes to the front, and everything large goes to the back:'''
|
||||||
|
|
||||||
|
|
||||||
|
from linked_list_fifo import LinkedListFIFO
|
||||||
|
from node import Node
|
||||||
|
|
||||||
|
|
||||||
|
def partList(ll, n):
|
||||||
|
|
||||||
|
more = LinkedListFIFO()
|
||||||
|
less = LinkedListFIFO()
|
||||||
|
|
||||||
|
node = ll.head
|
||||||
|
|
||||||
|
while node:
|
||||||
|
item = node.value
|
||||||
|
|
||||||
|
if item < n:
|
||||||
|
less.addNode(item)
|
||||||
|
|
||||||
|
elif item > n:
|
||||||
|
more.addNode(item)
|
||||||
|
|
||||||
|
node = node.pointer
|
||||||
|
|
||||||
|
less.addNode(n)
|
||||||
|
nodemore = more.head
|
||||||
|
|
||||||
|
while nodemore:
|
||||||
|
less.addNode(nodemore.value)
|
||||||
|
nodemore = nodemore.pointer
|
||||||
|
|
||||||
|
return less
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
|
||||||
|
ll = LinkedListFIFO()
|
||||||
|
l = [6, 7, 3, 4, 9, 5, 1, 2, 8]
|
||||||
|
for i in l:
|
||||||
|
ll.addNode(i)
|
||||||
|
|
||||||
|
print('Before Part')
|
||||||
|
ll._printList()
|
||||||
|
|
||||||
|
print('After Part')
|
||||||
|
newll = partList(ll, 6)
|
||||||
|
newll._printList()
|
||||||
|
|
||||||
|
|
@ -0,0 +1,85 @@
|
|||||||
|
#!/usr/bin/env python
|
||||||
|
|
||||||
|
__author__ = "bt3"
|
||||||
|
|
||||||
|
''' Supposing two linked lists representing numbers, such that in each of their
|
||||||
|
nodes they carry one digit. This function sums the two numbers that these
|
||||||
|
two linked lists represent, returning a third list representing the sum:'''
|
||||||
|
|
||||||
|
|
||||||
|
from linked_list_fifo import LinkedListFIFO
|
||||||
|
from node import Node
|
||||||
|
|
||||||
|
|
||||||
|
class LinkedListFIFOYield(LinkedListFIFO):
|
||||||
|
|
||||||
|
# print each node's value, starting from the head
|
||||||
|
def _printList(self):
|
||||||
|
node = self.head
|
||||||
|
while node:
|
||||||
|
yield(node.value)
|
||||||
|
node = node.pointer
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
def sumlls(l1, l2):
|
||||||
|
|
||||||
|
lsum = LinkedListFIFOYield()
|
||||||
|
dig1 = l1.head
|
||||||
|
dig2 = l2.head
|
||||||
|
pointer = 0
|
||||||
|
|
||||||
|
while dig1 and dig2:
|
||||||
|
d1 = dig1.value
|
||||||
|
d2 = dig2.value
|
||||||
|
sum_d = d1 + d2 + pointer
|
||||||
|
if sum_d > 9:
|
||||||
|
pointer = sum_d//10
|
||||||
|
lsum.addNode(sum_d%10)
|
||||||
|
|
||||||
|
else:
|
||||||
|
lsum.addNode(sum_d)
|
||||||
|
pointer = 0
|
||||||
|
|
||||||
|
dig1 = dig1.pointer
|
||||||
|
dig2 = dig2.pointer
|
||||||
|
|
||||||
|
if dig1:
|
||||||
|
sum_d = pointer + dig1.value
|
||||||
|
if sum_d > 9:
|
||||||
|
lsum.addNode(sum_d%10)
|
||||||
|
else:
|
||||||
|
lsum.addNode(sum_d)
|
||||||
|
dig1 = dig1.pointer
|
||||||
|
|
||||||
|
if dig2:
|
||||||
|
sum_d = pointer + dig2.value
|
||||||
|
if sum_d > 9:
|
||||||
|
lsum.addNode(sum_d%10)
|
||||||
|
else:
|
||||||
|
lsum.addNode(sum_d)
|
||||||
|
dig2 = dig2.pointer
|
||||||
|
|
||||||
|
return lsum
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
l1 = LinkedListFIFOYield() # 2671
|
||||||
|
l1.addNode(1)
|
||||||
|
l1.addNode(7)
|
||||||
|
l1.addNode(6)
|
||||||
|
l1.addNode(2)
|
||||||
|
|
||||||
|
l2 = LinkedListFIFOYield() # 455
|
||||||
|
l2.addNode(5)
|
||||||
|
l2.addNode(5)
|
||||||
|
l2.addNode(4)
|
||||||
|
|
||||||
|
lsum = sumlls(l1, l2)
|
||||||
|
l = list(lsum._printList())
|
||||||
|
for i in reversed(l):
|
||||||
|
print i
|
@ -0,0 +1,109 @@
|
|||||||
|
#!/usr/bin/env python
|
||||||
|
|
||||||
|
__author__ = "bt3"
|
||||||
|
|
||||||
|
|
||||||
|
""" A class for an animal shelter with two queues"""
|
||||||
|
|
||||||
|
|
||||||
|
class Node(object):
|
||||||
|
def __init__(self, animalName=None, animalKind=None, pointer=None):
|
||||||
|
self.animalName = animalName
|
||||||
|
self.animalKind = animalKind
|
||||||
|
self.pointer = pointer
|
||||||
|
self.timestamp = 0
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
class AnimalShelter(object):
|
||||||
|
def __init__(self):
|
||||||
|
self.headCat = None
|
||||||
|
self.headDog = None
|
||||||
|
self.tailCat = None
|
||||||
|
self.tailDog = None
|
||||||
|
self.animalNumber = 0
|
||||||
|
|
||||||
|
|
||||||
|
# Queue any animal
|
||||||
|
|
||||||
|
def enqueue(self, animalName, animalKind):
|
||||||
|
self.animalNumber += 1
|
||||||
|
newAnimal = Node(animalName, animalKind)
|
||||||
|
newAnimal.timestamp = self.animalNumber
|
||||||
|
|
||||||
|
if animalKind == 'cat':
|
||||||
|
if not self.headCat:
|
||||||
|
self.headCat = newAnimal
|
||||||
|
if self.tailCat:
|
||||||
|
self.tailCat.pointer = newAnimal
|
||||||
|
self.tailCat = newAnimal
|
||||||
|
|
||||||
|
elif animalKind == 'dog':
|
||||||
|
if not self.headDog:
|
||||||
|
self.headDog = newAnimal
|
||||||
|
if self.tailDog:
|
||||||
|
self.tailDog.pointer = newAnimal
|
||||||
|
self.tailDog = newAnimal
|
||||||
|
|
||||||
|
|
||||||
|
# Dequeue methods
|
||||||
|
|
||||||
|
def dequeueDog(self):
|
||||||
|
if self.headDog:
|
||||||
|
newAnimal = self.headDog
|
||||||
|
self.headDog = newAnimal.pointer
|
||||||
|
return str(newAnimal.animalName)
|
||||||
|
else:
|
||||||
|
return 'No Dogs!'
|
||||||
|
|
||||||
|
|
||||||
|
def dequeueCat(self):
|
||||||
|
if self.headCat:
|
||||||
|
newAnimal = self.headCat
|
||||||
|
self.headCat = newAnimal.pointer
|
||||||
|
return str(newAnimal.animalName)
|
||||||
|
else:
|
||||||
|
return 'No Cats!'
|
||||||
|
|
||||||
|
|
||||||
|
def dequeueAny(self):
|
||||||
|
if self.headCat and not self.headDog:
|
||||||
|
return self.dequeueCat()
|
||||||
|
elif self.headDog and not self.headCat:
|
||||||
|
return self.dequeueDog()
|
||||||
|
elif self.headDog and self.headCat:
|
||||||
|
if self.headDog.timestamp < self.headCat.timestamp:
|
||||||
|
return self.dequeueDog()
|
||||||
|
else:
|
||||||
|
return self.dequeueCat()
|
||||||
|
else:
|
||||||
|
return ('No Animals!')
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
def _print(self):
|
||||||
|
print("Cats:")
|
||||||
|
cats = self.headCat
|
||||||
|
while cats:
|
||||||
|
print(cats.animalName, cats.animalKind)
|
||||||
|
cats = cats.pointer
|
||||||
|
print("Dogs:")
|
||||||
|
dogs = self.headDog
|
||||||
|
while dogs:
|
||||||
|
print(dogs.animalName, dogs.animalKind)
|
||||||
|
dogs = dogs.pointer
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
|
||||||
|
qs = AnimalShelter()
|
||||||
|
qs.enqueue('bob', 'cat')
|
||||||
|
qs.enqueue('mia', 'cat')
|
||||||
|
qs.enqueue('yoda', 'dog')
|
||||||
|
qs.enqueue('wolf', 'dog')
|
||||||
|
qs._print()
|
||||||
|
|
||||||
|
print("Deque one dog and one cat...")
|
||||||
|
qs.dequeueDog()
|
||||||
|
qs.dequeueCat()
|
||||||
|
qs._print()
|
@ -0,0 +1,39 @@
|
|||||||
|
#!/usr/bin/env python
|
||||||
|
|
||||||
|
__author__ = "bt3"
|
||||||
|
|
||||||
|
''' a class for a double ended queue (also inefficient) '''
|
||||||
|
|
||||||
|
from queue import Queue
|
||||||
|
|
||||||
|
class Deque(Queue):
|
||||||
|
|
||||||
|
def enqueue_back(self, item):
|
||||||
|
self.items.append(item)
|
||||||
|
|
||||||
|
def dequeue_front(self):
|
||||||
|
return self.items.pop(0)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
queue = Deque()
|
||||||
|
print("Is the queue empty? ", queue.isEmpty())
|
||||||
|
print("Adding 0 to 10 in the queue...")
|
||||||
|
for i in range(10):
|
||||||
|
queue.enqueue(i)
|
||||||
|
print("Queue size: ", queue.size())
|
||||||
|
print("Queue peek : ", queue.peek())
|
||||||
|
print("Dequeue...", queue.dequeue())
|
||||||
|
print("Queue peek: ", queue.peek())
|
||||||
|
print("Is the queue empty? ", queue.isEmpty())
|
||||||
|
print(queue)
|
||||||
|
|
||||||
|
print("\nNow using the dequeue methods...")
|
||||||
|
print("Dequeue from front...", queue.dequeue_front())
|
||||||
|
print("Queue peek: ", queue.peek())
|
||||||
|
print(queue)
|
||||||
|
print("Queue from back...")
|
||||||
|
queue.enqueue_back(50)
|
||||||
|
print("Queue peek: ", queue.peek())
|
||||||
|
print(queue)
|
@ -0,0 +1,80 @@
|
|||||||
|
#!/usr/bin/env python
|
||||||
|
|
||||||
|
__author__ = "bt3"
|
||||||
|
|
||||||
|
''' Queue acts as a container for nodes (objects) that are inserted and removed according FIFO'''
|
||||||
|
|
||||||
|
|
||||||
|
class Node(object):
|
||||||
|
def __init__(self, value=None, pointer=None):
|
||||||
|
self.value = value
|
||||||
|
self.pointer = None
|
||||||
|
|
||||||
|
|
||||||
|
class LinkedQueue(object):
|
||||||
|
def __init__(self):
|
||||||
|
self.head = None
|
||||||
|
self.tail = None
|
||||||
|
|
||||||
|
|
||||||
|
def isEmpty(self):
|
||||||
|
return not bool(self.head)
|
||||||
|
|
||||||
|
|
||||||
|
def dequeue(self):
|
||||||
|
if self.head:
|
||||||
|
value = self.head.value
|
||||||
|
self.head = self.head.pointer
|
||||||
|
return value
|
||||||
|
else:
|
||||||
|
print('Queue is empty, cannot dequeue.')
|
||||||
|
|
||||||
|
|
||||||
|
def enqueue(self, value):
|
||||||
|
node = Node(value)
|
||||||
|
if not self.head:
|
||||||
|
self.head = node
|
||||||
|
self.tail = node
|
||||||
|
else:
|
||||||
|
if self.tail:
|
||||||
|
self.tail.pointer = node
|
||||||
|
self.tail = node
|
||||||
|
|
||||||
|
|
||||||
|
def size(self):
|
||||||
|
node = self.head
|
||||||
|
num_nodes = 0
|
||||||
|
while node:
|
||||||
|
num_nodes += 1
|
||||||
|
node = node.pointer
|
||||||
|
return num_nodes
|
||||||
|
|
||||||
|
|
||||||
|
def peek(self):
|
||||||
|
return self.head.value
|
||||||
|
|
||||||
|
|
||||||
|
def _print(self):
|
||||||
|
node = self.head
|
||||||
|
while node:
|
||||||
|
print(node.value)
|
||||||
|
node = node.pointer
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
queue = LinkedQueue()
|
||||||
|
print("Is the queue empty? ", queue.isEmpty())
|
||||||
|
print("Adding 0 to 10 in the queue...")
|
||||||
|
for i in range(10):
|
||||||
|
queue.enqueue(i)
|
||||||
|
print("Is the queue empty? ", queue.isEmpty())
|
||||||
|
queue._print()
|
||||||
|
|
||||||
|
print("Queue size: ", queue.size())
|
||||||
|
print("Queue peek : ", queue.peek())
|
||||||
|
print("Dequeue...", queue.dequeue())
|
||||||
|
print("Queue peek: ", queue.peek())
|
||||||
|
queue._print()
|
||||||
|
|
@ -0,0 +1,47 @@
|
|||||||
|
#!/usr/bin/env python
|
||||||
|
|
||||||
|
__author__ = "bt3"
|
||||||
|
|
||||||
|
|
||||||
|
""" Using our deque class and Python's deque class """
|
||||||
|
|
||||||
|
|
||||||
|
import string
|
||||||
|
import collections
|
||||||
|
|
||||||
|
from deque import Deque
|
||||||
|
|
||||||
|
|
||||||
|
STRIP = string.whitespace + string.punctuation + "\"'"
|
||||||
|
|
||||||
|
def palindrome_checker_with_deque(str1):
|
||||||
|
|
||||||
|
d1 = Deque()
|
||||||
|
d2 = collections.deque()
|
||||||
|
|
||||||
|
for s in str1.lower():
|
||||||
|
if s not in STRIP:
|
||||||
|
d2.append(s)
|
||||||
|
d1.enqueue(s)
|
||||||
|
|
||||||
|
|
||||||
|
eq1 = True
|
||||||
|
while d1.size() > 1 and eq1:
|
||||||
|
if d1.dequeue_front() != d1.dequeue():
|
||||||
|
eq1 = False
|
||||||
|
|
||||||
|
eq2 = True
|
||||||
|
while len(d2) > 1 and eq2:
|
||||||
|
if d2.pop() != d2.popleft():
|
||||||
|
eq2 = False
|
||||||
|
|
||||||
|
return eq1, eq2
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
str1 = 'Madam Im Adam'
|
||||||
|
str2 = 'Buffy is a Slayer'
|
||||||
|
print(palindrome_checker_with_deque(str1))
|
||||||
|
print(palindrome_checker_with_deque(str2))
|
@ -0,0 +1,63 @@
|
|||||||
|
#!/usr/bin/env python
|
||||||
|
|
||||||
|
__author__ = "bt3"
|
||||||
|
|
||||||
|
|
||||||
|
class Queue(object):
|
||||||
|
|
||||||
|
def __init__(self):
|
||||||
|
self.in_stack = []
|
||||||
|
self.out_stack = []
|
||||||
|
|
||||||
|
def _transfer(self):
|
||||||
|
while self.in_stack:
|
||||||
|
self.out_stack.append(self.in_stack.pop())
|
||||||
|
|
||||||
|
def enqueue(self, item):
|
||||||
|
return self.in_stack.append(item)
|
||||||
|
|
||||||
|
def dequeue(self):
|
||||||
|
if not self.out_stack:
|
||||||
|
self._transfer()
|
||||||
|
if self.out_stack:
|
||||||
|
return self.out_stack.pop()
|
||||||
|
else:
|
||||||
|
return "Queue empty!"
|
||||||
|
|
||||||
|
def size(self):
|
||||||
|
return len(self.in_stack) + len(self.out_stack)
|
||||||
|
|
||||||
|
def peek(self):
|
||||||
|
if not self.out_stack:
|
||||||
|
self._transfer()
|
||||||
|
if self.out_stack:
|
||||||
|
return self.out_stack[-1]
|
||||||
|
else:
|
||||||
|
return "Queue empty!"
|
||||||
|
|
||||||
|
def __repr__(self):
|
||||||
|
if not self.out_stack:
|
||||||
|
self._transfer()
|
||||||
|
if self.out_stack:
|
||||||
|
return '{}'.format(self.out_stack)
|
||||||
|
else:
|
||||||
|
return "Queue empty!"
|
||||||
|
|
||||||
|
def isEmpty(self):
|
||||||
|
return not (bool(self.in_stack) or bool(self.out_stack))
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
queue = Queue()
|
||||||
|
print("Is the queue empty? ", queue.isEmpty())
|
||||||
|
print("Adding 0 to 10 in the queue...")
|
||||||
|
for i in range(10):
|
||||||
|
queue.enqueue(i)
|
||||||
|
print("Queue size: ", queue.size())
|
||||||
|
print("Queue peek : ", queue.peek())
|
||||||
|
print("Dequeue...", queue.dequeue())
|
||||||
|
print("Queue peek: ", queue.peek())
|
||||||
|
print("Is the queue empty? ", queue.isEmpty())
|
||||||
|
|
||||||
|
print("Printing the queue...")
|
||||||
|
print(queue)
|
@ -0,0 +1,30 @@
|
|||||||
|
#!/usr/bin/env python
|
||||||
|
|
||||||
|
__author__ = "bt3"
|
||||||
|
|
||||||
|
|
||||||
|
'''transform a decimal number to a binary number with a stack '''
|
||||||
|
|
||||||
|
|
||||||
|
from stack import Stack
|
||||||
|
|
||||||
|
def dec2bin_with_stack(decnum):
|
||||||
|
|
||||||
|
s = Stack()
|
||||||
|
str_aux = ''
|
||||||
|
|
||||||
|
while decnum > 0:
|
||||||
|
dig = decnum % 2
|
||||||
|
decnum = decnum//2
|
||||||
|
s.push(dig)
|
||||||
|
|
||||||
|
while not s.isEmpty():
|
||||||
|
str_aux += str(s.pop())
|
||||||
|
|
||||||
|
return str_aux
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
decnum = 9
|
||||||
|
assert(dec2bin_with_stack(decnum) == '1001')
|
@ -0,0 +1,71 @@
|
|||||||
|
#!/usr/bin/env python
|
||||||
|
|
||||||
|
__author__ = "bt3"
|
||||||
|
|
||||||
|
|
||||||
|
""" A stack made of linked list"""
|
||||||
|
|
||||||
|
|
||||||
|
class Node(object):
|
||||||
|
def __init__(self, value=None, pointer=None):
|
||||||
|
self.value = value
|
||||||
|
self.pointer = pointer
|
||||||
|
|
||||||
|
|
||||||
|
class Stack(object):
|
||||||
|
def __init__(self):
|
||||||
|
self.head = None
|
||||||
|
|
||||||
|
def isEmpty(self):
|
||||||
|
return not bool(self.head)
|
||||||
|
|
||||||
|
def push(self, item):
|
||||||
|
self.head = Node(item, self.head)
|
||||||
|
|
||||||
|
|
||||||
|
def pop(self):
|
||||||
|
if self.head:
|
||||||
|
node = self.head
|
||||||
|
self.head = node.pointer
|
||||||
|
return node.value
|
||||||
|
else:
|
||||||
|
print('Stack is empty.')
|
||||||
|
|
||||||
|
|
||||||
|
def peek(self):
|
||||||
|
if self.head:
|
||||||
|
return self.head.value
|
||||||
|
else:
|
||||||
|
print('Stack is empty.')
|
||||||
|
|
||||||
|
|
||||||
|
def size(self):
|
||||||
|
node = self.head
|
||||||
|
count = 0
|
||||||
|
while node:
|
||||||
|
count +=1
|
||||||
|
node = node.pointer
|
||||||
|
return count
|
||||||
|
|
||||||
|
|
||||||
|
def _printList(self):
|
||||||
|
node = self.head
|
||||||
|
while node:
|
||||||
|
print(node.value)
|
||||||
|
node = node.pointer
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
stack = Stack()
|
||||||
|
print("Is the stack empty? ", stack.isEmpty())
|
||||||
|
print("Adding 0 to 10 in the stack...")
|
||||||
|
for i in range(10):
|
||||||
|
stack.push(i)
|
||||||
|
stack._printList()
|
||||||
|
print("Stack size: ", stack.size())
|
||||||
|
print("Stack peek : ", stack.peek())
|
||||||
|
print("Pop...", stack.pop())
|
||||||
|
print("Stack peek: ", stack.peek())
|
||||||
|
print("Is the stack empty? ", stack.isEmpty())
|
||||||
|
stack._printList()
|
@ -0,0 +1,31 @@
|
|||||||
|
#!/usr/bin/env python
|
||||||
|
|
||||||
|
__author__ = "bt3"
|
||||||
|
|
||||||
|
|
||||||
|
''' Uses a stack to reverse a string '''
|
||||||
|
|
||||||
|
from stack import Stack
|
||||||
|
|
||||||
|
def reverse_string_with_stack(str1):
|
||||||
|
|
||||||
|
s = Stack()
|
||||||
|
revStr = ''
|
||||||
|
|
||||||
|
for c in str1:
|
||||||
|
s.push(c)
|
||||||
|
|
||||||
|
while not s.isEmpty():
|
||||||
|
revStr += s.pop()
|
||||||
|
|
||||||
|
return revStr
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
str1 = 'Buffy is a Slayer!'
|
||||||
|
print(str1)
|
||||||
|
print(reverse_string_with_stack(str1))
|
||||||
|
|
||||||
|
|
||||||
|
|
@ -0,0 +1,56 @@
|
|||||||
|
#!/usr/bin/env python
|
||||||
|
|
||||||
|
__author__ = "bt3"
|
||||||
|
|
||||||
|
""" define a class for a set of stacks """
|
||||||
|
|
||||||
|
from stack import Stack
|
||||||
|
|
||||||
|
class SetOfStacks(Stack):
|
||||||
|
def __init__(self, capacity=4):
|
||||||
|
self.setofstacks = []
|
||||||
|
self.items = []
|
||||||
|
self.capacity = capacity
|
||||||
|
|
||||||
|
|
||||||
|
def push(self, value):
|
||||||
|
if self.size() >= self.capacity:
|
||||||
|
self.setofstacks.append(self.items)
|
||||||
|
self.items = []
|
||||||
|
self.items.append(value)
|
||||||
|
|
||||||
|
|
||||||
|
def pop(self):
|
||||||
|
value = self.items.pop()
|
||||||
|
if self.isEmpty() and self.setofstacks:
|
||||||
|
self.items = self.setofstacks.pop()
|
||||||
|
return value
|
||||||
|
|
||||||
|
|
||||||
|
def sizeStack(self):
|
||||||
|
return len(self.setofstacks)*self.capacity + self.size()
|
||||||
|
|
||||||
|
|
||||||
|
def __repr__(self):
|
||||||
|
aux = []
|
||||||
|
for s in self.setofstacks:
|
||||||
|
aux.extend(s)
|
||||||
|
aux.extend(self.items)
|
||||||
|
return '{}'.format(aux)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
capacity = 5
|
||||||
|
stack = SetOfStacks(capacity)
|
||||||
|
print("Is the stack empty? ", stack.isEmpty())
|
||||||
|
print("Adding 0 to 10 in the stack...")
|
||||||
|
for i in range(10):
|
||||||
|
stack.push(i)
|
||||||
|
print(stack)
|
||||||
|
print("Stack size: ", stack.sizeStack())
|
||||||
|
print("Stack peek : ", stack.peek())
|
||||||
|
print("Pop...", stack.pop())
|
||||||
|
print("Stack peek: ", stack.peek())
|
||||||
|
print("Is the stack empty? ", stack.isEmpty())
|
||||||
|
print(stack)
|
65
First_edition_2014/ebook_src/abstract_structures/stacks/stack.py
Executable file
65
First_edition_2014/ebook_src/abstract_structures/stacks/stack.py
Executable file
@ -0,0 +1,65 @@
|
|||||||
|
#!/usr/bin/env python
|
||||||
|
|
||||||
|
# copy of the class ../Stack.py
|
||||||
|
|
||||||
|
__author__ = "bt3"
|
||||||
|
|
||||||
|
|
||||||
|
class Stack(object):
|
||||||
|
def __init__(self):
|
||||||
|
self.content = []
|
||||||
|
self.min_array = []
|
||||||
|
self.min = float('inf')
|
||||||
|
|
||||||
|
def push(self, value):
|
||||||
|
if value < self.min:
|
||||||
|
self.min = value
|
||||||
|
|
||||||
|
self.content.append(value)
|
||||||
|
self.min_array.append(self.min)
|
||||||
|
|
||||||
|
def pop(self):
|
||||||
|
if self.content:
|
||||||
|
value = self.content.pop()
|
||||||
|
self.min_array.pop()
|
||||||
|
if self.min_array:
|
||||||
|
self.min = self.min_array[-1]
|
||||||
|
return value
|
||||||
|
else:
|
||||||
|
return 'Empty List. '
|
||||||
|
|
||||||
|
def find_min(self):
|
||||||
|
if self.min_array:
|
||||||
|
return self.min_array[-1]
|
||||||
|
else:
|
||||||
|
return 'No min value for empty list.'
|
||||||
|
|
||||||
|
def size(self):
|
||||||
|
return len(self.content)
|
||||||
|
|
||||||
|
def isEmpty(self):
|
||||||
|
return not bool(self.content)
|
||||||
|
|
||||||
|
def peek(self):
|
||||||
|
if self.content:
|
||||||
|
return self.content[-1]
|
||||||
|
else:
|
||||||
|
print('Stack is empty.')
|
||||||
|
|
||||||
|
|
||||||
|
def __repr__(self):
|
||||||
|
return '{}'.format(self.content)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
q = Stack()
|
||||||
|
|
||||||
|
for i in range(15,20):
|
||||||
|
q.push(i)
|
||||||
|
for i in range(10,5,-1):
|
||||||
|
q.push(i)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
for i in range(1, 13):
|
||||||
|
print q.pop(), q.find_min()
|
@ -0,0 +1,77 @@
|
|||||||
|
#!/usr/bin/env python
|
||||||
|
|
||||||
|
__author__ = "bt3"
|
||||||
|
|
||||||
|
''' A stack with a minimum lookup '''
|
||||||
|
|
||||||
|
from stack import Stack
|
||||||
|
|
||||||
|
|
||||||
|
class NodeWithMin(object):
|
||||||
|
def __init__(self, value=None, minimum=None):
|
||||||
|
self.value = value
|
||||||
|
self.minimum = minimum
|
||||||
|
|
||||||
|
|
||||||
|
class StackMin(Stack):
|
||||||
|
def __init__(self):
|
||||||
|
self.items = []
|
||||||
|
self.minimum = None
|
||||||
|
|
||||||
|
|
||||||
|
def push(self, value):
|
||||||
|
if self.isEmpty() or self.minimum > value:
|
||||||
|
self.minimum = value
|
||||||
|
self.items.append(NodeWithMin(value, self.minimum))
|
||||||
|
|
||||||
|
|
||||||
|
def peek(self):
|
||||||
|
return self.items[-1].value
|
||||||
|
|
||||||
|
|
||||||
|
def peekMinimum(self):
|
||||||
|
return self.items[-1].minimum
|
||||||
|
|
||||||
|
|
||||||
|
def pop(self):
|
||||||
|
item = self.items.pop()
|
||||||
|
if item:
|
||||||
|
if item.value == self.minimum:
|
||||||
|
self.minimum = self.peekMinimum()
|
||||||
|
return item.value
|
||||||
|
else:
|
||||||
|
print("Stack is empty.")
|
||||||
|
|
||||||
|
def __repr__(self):
|
||||||
|
aux = []
|
||||||
|
for i in self.items:
|
||||||
|
aux.append(i.value)
|
||||||
|
return '{}'.format(aux)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
stack = StackMin()
|
||||||
|
print("Is the stack empty? ", stack.isEmpty())
|
||||||
|
print("Adding 0 to 10 in the stack...")
|
||||||
|
for i in range(10,3, -1):
|
||||||
|
stack.push(i)
|
||||||
|
print(stack)
|
||||||
|
|
||||||
|
print("Stack size: ", stack.size())
|
||||||
|
print("Stack peek and peekMinimum : ", stack.peek(), stack.peekMinimum())
|
||||||
|
print("Pop...", stack.pop())
|
||||||
|
print("Stack peek and peekMinimum : ", stack.peek(), stack.peekMinimum())
|
||||||
|
print("Is the stack empty? ", stack.isEmpty())
|
||||||
|
print(stack)
|
||||||
|
|
||||||
|
for i in range(5, 1, -1):
|
||||||
|
stack.push(i)
|
||||||
|
print(stack)
|
||||||
|
|
||||||
|
print("Stack size: ", stack.size())
|
||||||
|
print("Stack peek and peekMinimum : ", stack.peek(), stack.peekMinimum())
|
||||||
|
print("Pop...", stack.pop())
|
||||||
|
print("Stack peek and peekMinimum : ", stack.peek(), stack.peekMinimum())
|
||||||
|
print("Is the stack empty? ", stack.isEmpty())
|
||||||
|
print(stack)
|
@ -0,0 +1,41 @@
|
|||||||
|
#!/usr/bin/env python
|
||||||
|
|
||||||
|
__author__ = "bt3"
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
""" Implement the 'towers of hanoi'"""
|
||||||
|
|
||||||
|
from linked_stack import Stack, Node
|
||||||
|
|
||||||
|
|
||||||
|
def moveTop(s1, s3):
|
||||||
|
|
||||||
|
s3.append(s1.pop())
|
||||||
|
|
||||||
|
|
||||||
|
def moveDisks(n, s1, s3, s2):
|
||||||
|
|
||||||
|
if n < 1: return
|
||||||
|
moveDisks(n - 1, s1, s2, s3)
|
||||||
|
moveTop(s1, s3)
|
||||||
|
moveDisks(n -1, s2, s3, s1)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
def towersOfHanoi(n):
|
||||||
|
s1 = [x+1 for x in range(n)]
|
||||||
|
s2 = []
|
||||||
|
s3 = []
|
||||||
|
print('The first stick is {0} and the third stick has {1}'.format(s1, s3))
|
||||||
|
|
||||||
|
moveDisks(n, s1, s3, s2)
|
||||||
|
|
||||||
|
print('The first stick is {0} and the third stick has {1}'.format(s1, s3))
|
||||||
|
|
||||||
|
return s3
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
towersOfHanoi(6)
|
28
First_edition_2014/ebook_src/bitwise/bit_array.py
Executable file
28
First_edition_2014/ebook_src/bitwise/bit_array.py
Executable file
@ -0,0 +1,28 @@
|
|||||||
|
#!/usr/bin/env python
|
||||||
|
|
||||||
|
__author__ = "bt3"
|
||||||
|
|
||||||
|
''' Example of how to use a bit array in python as a "counter" dict'''
|
||||||
|
|
||||||
|
def print_dupl_ba(l1):
|
||||||
|
'''
|
||||||
|
>>> l1 = [0, 1, 2, 3, 4, 2, 6, 7, 8, 9]
|
||||||
|
>>> print_dupl_ba(l1)
|
||||||
|
2
|
||||||
|
'''
|
||||||
|
|
||||||
|
bs = bytearray(10)
|
||||||
|
for i in range(len(l1)):
|
||||||
|
if i == l1[i]:
|
||||||
|
bs[i] = 1
|
||||||
|
for index, bit in enumerate(bs):
|
||||||
|
if bit == 0:
|
||||||
|
return l1[index]
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
import doctest
|
||||||
|
doctest.testmod()
|
||||||
|
|
33
First_edition_2014/ebook_src/bitwise/bitwise.txt
Executable file
33
First_edition_2014/ebook_src/bitwise/bitwise.txt
Executable file
@ -0,0 +1,33 @@
|
|||||||
|
BIT-WISE
|
||||||
|
----------------------
|
||||||
|
|
||||||
|
1. To find a number:
|
||||||
|
11000101 is 2^0+2^2+2^6+2^7 = 197
|
||||||
|
|
||||||
|
|
||||||
|
2. Left shifting:
|
||||||
|
0010 1011 << 4 ---> 1011 000
|
||||||
|
|
||||||
|
|
||||||
|
3. Right shifting:
|
||||||
|
0010 1011 >> 4 ---> 0000 0010
|
||||||
|
or it can be filled with the copy of the first bit, instead of 0:
|
||||||
|
1011 0010 >> 4 ---> 1111 1011
|
||||||
|
|
||||||
|
|
||||||
|
4. XOR can cancels out:
|
||||||
|
15 ^ 12 ^ 15 = 12
|
||||||
|
|
||||||
|
|
||||||
|
5. 2^x:
|
||||||
|
left-shift 1 by x:
|
||||||
|
0000 0001 << x
|
||||||
|
|
||||||
|
so if x = 2, 2^2 = 4 -> 100
|
||||||
|
|
||||||
|
0000 0001 << 2 ---> 0000 0100
|
||||||
|
|
||||||
|
|
||||||
|
6. Is power of 2?
|
||||||
|
just do x&(x-1).
|
||||||
|
if 0 --> yes!
|
37
First_edition_2014/ebook_src/bitwise/clear_bits.py
Executable file
37
First_edition_2014/ebook_src/bitwise/clear_bits.py
Executable file
@ -0,0 +1,37 @@
|
|||||||
|
#!/usr/bin/env python
|
||||||
|
|
||||||
|
__author__ = "bt3"
|
||||||
|
|
||||||
|
''' Clear a bit in a binary number.
|
||||||
|
Like the reverse of set bit:
|
||||||
|
1) first create a number filled of 1s,
|
||||||
|
with 0 at i (can create 0001000 and ~)
|
||||||
|
2) AND the number so it clears the ith bit
|
||||||
|
'''
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
def clear_bit(num, i):
|
||||||
|
mask = ~ (1 << i) # -0b10001
|
||||||
|
return bin(num & mask)
|
||||||
|
|
||||||
|
|
||||||
|
def clear_all_bits_from_i_to_0(num, i):
|
||||||
|
mask = ~ ( (1 << (i+1)) - 1)
|
||||||
|
return bin(num & mask)
|
||||||
|
|
||||||
|
|
||||||
|
def clear_all_bits_from_most_sig_to_1(num, i):
|
||||||
|
mask = ( 1 << i) -1
|
||||||
|
return bin(num & mask)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
num = int('10010000', 2)
|
||||||
|
print clear_bit(num, 4) # '0b10000000'
|
||||||
|
|
||||||
|
num = int('10010011', 2)
|
||||||
|
print clear_all_bits_from_i_to_0(num, 2) # '0b10010000'
|
||||||
|
|
||||||
|
num = int('1110011', 2)
|
||||||
|
print clear_all_bits_from_most_sig_to_1(num, 2) #'0b11'
|
25
First_edition_2014/ebook_src/bitwise/find_bit_len.py
Executable file
25
First_edition_2014/ebook_src/bitwise/find_bit_len.py
Executable file
@ -0,0 +1,25 @@
|
|||||||
|
#!/usr/bin/env python
|
||||||
|
|
||||||
|
__author__ = "bt3"
|
||||||
|
|
||||||
|
''' Find how many bits a int has:
|
||||||
|
1) Start with a mask of 1
|
||||||
|
2) Mask with AND
|
||||||
|
3) if result (if true): count += 1
|
||||||
|
(obs: to find the int of a bin do int('1001', 2)) and to show in bin
|
||||||
|
do bin(int))
|
||||||
|
'''
|
||||||
|
|
||||||
|
|
||||||
|
def find_bit_len(int_num):
|
||||||
|
lenght = 0
|
||||||
|
while int_num:
|
||||||
|
int_num >>= 1
|
||||||
|
lenght += 1
|
||||||
|
return lenght
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
for i in range(17):
|
||||||
|
print(find_bit_len(i))
|
||||||
|
print i.bit_length()
|
32
First_edition_2014/ebook_src/bitwise/find_how_many_1_binary.py
Executable file
32
First_edition_2014/ebook_src/bitwise/find_how_many_1_binary.py
Executable file
@ -0,0 +1,32 @@
|
|||||||
|
#!/usr/bin/env python
|
||||||
|
|
||||||
|
__author__ = "bt3"
|
||||||
|
|
||||||
|
''' Find how many 1s in the binary:
|
||||||
|
1) Start with a mask of 1
|
||||||
|
2) Mask with AND
|
||||||
|
3) if result (if true): count += 1
|
||||||
|
(obs: to find the int of a bin do int('1001',
|
||||||
|
2)) and to show in bin do bin(int))
|
||||||
|
'''
|
||||||
|
|
||||||
|
|
||||||
|
def find_how_many_1_in_a_binary(n):
|
||||||
|
'''
|
||||||
|
>>> find_how_many_1_in_a_binary(9)
|
||||||
|
2
|
||||||
|
'''
|
||||||
|
|
||||||
|
counter = 0
|
||||||
|
while n:
|
||||||
|
if n & 1:
|
||||||
|
counter += 1
|
||||||
|
n >>= 1
|
||||||
|
return counter
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
import doctest
|
||||||
|
doctest.testmod()
|
||||||
|
|
27
First_edition_2014/ebook_src/bitwise/get_bit.py
Executable file
27
First_edition_2014/ebook_src/bitwise/get_bit.py
Executable file
@ -0,0 +1,27 @@
|
|||||||
|
#!/usr/bin/env python
|
||||||
|
|
||||||
|
__author__ = "bt3"
|
||||||
|
|
||||||
|
''' Get a bit in a binary number:
|
||||||
|
1) Shifts 1 over by i bits
|
||||||
|
2) make an AND with the number
|
||||||
|
3) all the other than the bit at i are clean, now compare to 0
|
||||||
|
4) if the new value is not 0, bit i is 1
|
||||||
|
'''
|
||||||
|
|
||||||
|
|
||||||
|
def get_bit(num, i):
|
||||||
|
mask = 1 << i
|
||||||
|
return num & mask != 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
num = int('0100100', 2)
|
||||||
|
get_bit(num, 0) # 0
|
||||||
|
get_bit(num, 1) # 0
|
||||||
|
get_bit(num, 2) # 1
|
||||||
|
get_bit(num, 3) # 0
|
||||||
|
get_bit(num, 4) # 0
|
||||||
|
get_bit(num, 5) # 1
|
||||||
|
get_bit(num, 6) # 0
|
||||||
|
|
37
First_edition_2014/ebook_src/bitwise/get_float_rep_bin.py
Executable file
37
First_edition_2014/ebook_src/bitwise/get_float_rep_bin.py
Executable file
@ -0,0 +1,37 @@
|
|||||||
|
#!/usr/bin/env python
|
||||||
|
|
||||||
|
__author__ = "bt3"
|
||||||
|
|
||||||
|
''' Given a real number between 0 and 1 (eg: 0.72), this method print the binary
|
||||||
|
representation. If the Number cannot be represented accurately in binary, with at
|
||||||
|
most 32 chars, print error:
|
||||||
|
'''
|
||||||
|
|
||||||
|
def get_float_rep(num):
|
||||||
|
'''
|
||||||
|
>>> get_float_rep(0.72)
|
||||||
|
('Error 2', '.1011100001010001111010111000010')
|
||||||
|
>>> get_float_rep(0.1)
|
||||||
|
('Error 2', '.0001100110011001100110011001100')
|
||||||
|
>>> get_float_rep(0.5)
|
||||||
|
'.1'
|
||||||
|
'''
|
||||||
|
|
||||||
|
if num >= 1 or num <= 0: return 'Error 1'
|
||||||
|
result = '.'
|
||||||
|
while num:
|
||||||
|
if len(result) >= 32: return 'Error 2', result
|
||||||
|
r = num*2
|
||||||
|
if r >= 1:
|
||||||
|
result += '1'
|
||||||
|
num = r - 1
|
||||||
|
else:
|
||||||
|
result += '0'
|
||||||
|
num = r
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
import doctest
|
||||||
|
doctest.testmod()
|
||||||
|
|
36
First_edition_2014/ebook_src/bitwise/insert_small_bin_into_big_bin.py
Executable file
36
First_edition_2014/ebook_src/bitwise/insert_small_bin_into_big_bin.py
Executable file
@ -0,0 +1,36 @@
|
|||||||
|
#!/usr/bin/env python
|
||||||
|
|
||||||
|
__author__ = "bt3"
|
||||||
|
|
||||||
|
|
||||||
|
''' Given two 32-bit numbers, N and M, and two bit positions, i and j, this
|
||||||
|
method insert M into N such that M starts at bit j and ends at bit i:
|
||||||
|
1) clear the bits j thru i in N'
|
||||||
|
2) shift M so that it lines up with bits j thru i
|
||||||
|
3) merge M and N
|
||||||
|
'''
|
||||||
|
|
||||||
|
def insert_small_bin_into_big_bin(M, N, i, j):
|
||||||
|
'''
|
||||||
|
>>> N = 0b10000000000
|
||||||
|
>>> M = 0b10011
|
||||||
|
>>> j = 6
|
||||||
|
>>> i = 2
|
||||||
|
>>> insert_small_bin_into_big_bin(M, N, i, j)
|
||||||
|
'0b10001001100'
|
||||||
|
'''
|
||||||
|
|
||||||
|
allOnes = ~0
|
||||||
|
left = allOnes << (j+1) # 1110000
|
||||||
|
right = ( (1 << i) - 1) # 0000111
|
||||||
|
mask = left | right # 1110111
|
||||||
|
N_cleared = N & mask
|
||||||
|
M_shifted = M << i
|
||||||
|
|
||||||
|
return bin( N_cleared | M_shifted)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
import doctest
|
||||||
|
doctest.testmod()
|
||||||
|
|
59
First_edition_2014/ebook_src/bitwise/next_with_same_num_1s.py
Executable file
59
First_edition_2014/ebook_src/bitwise/next_with_same_num_1s.py
Executable file
@ -0,0 +1,59 @@
|
|||||||
|
#!/usr/bin/env python
|
||||||
|
|
||||||
|
__author__ = "bt3"
|
||||||
|
|
||||||
|
|
||||||
|
''' Give a positive int, print the next smallest and next largest ints with
|
||||||
|
same number of 1 bits.
|
||||||
|
The brute force is:
|
||||||
|
1) find number of 1 bits
|
||||||
|
2) loop above and down until find same, checking for each
|
||||||
|
'''
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
def print_prev_same_1s(num):
|
||||||
|
n1s = find_num_1s(num)
|
||||||
|
# find prev
|
||||||
|
i = num-1
|
||||||
|
while True:
|
||||||
|
n1s_here = find_num_1s(i)
|
||||||
|
if n1s_here == n1s:
|
||||||
|
return bin(i)
|
||||||
|
i -= 1
|
||||||
|
if i < 0:
|
||||||
|
return None
|
||||||
|
|
||||||
|
def print_next_same_1s(num):
|
||||||
|
n1s = find_num_1s(num)
|
||||||
|
# find next
|
||||||
|
i = num+1
|
||||||
|
while True:
|
||||||
|
n1s_here = find_num_1s(i)
|
||||||
|
if n1s_here == n1s:
|
||||||
|
return bin(i)
|
||||||
|
i += 1
|
||||||
|
if i < 0:
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
def find_num_1s(num):
|
||||||
|
counter = 0
|
||||||
|
while num:
|
||||||
|
if num & 1:
|
||||||
|
counter += 1
|
||||||
|
num >>= 1
|
||||||
|
return counter
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
num = 0b1001
|
||||||
|
n = '0b1010'
|
||||||
|
p = '0b110'
|
||||||
|
print_prev_same_1s(num) == p
|
||||||
|
print_next_same_1s(num) == n
|
||||||
|
|
40
First_edition_2014/ebook_src/bitwise/num_bits_to_convert_2_nums.py
Executable file
40
First_edition_2014/ebook_src/bitwise/num_bits_to_convert_2_nums.py
Executable file
@ -0,0 +1,40 @@
|
|||||||
|
#!/usr/bin/env python
|
||||||
|
|
||||||
|
__author__ = "bt3"
|
||||||
|
|
||||||
|
|
||||||
|
''' This method returns the number of bits that are necessary to change to convert two
|
||||||
|
numbers A and B:
|
||||||
|
1) XOR
|
||||||
|
2) count 1s
|
||||||
|
'''
|
||||||
|
|
||||||
|
def count_bits_swap2(a, b):
|
||||||
|
count = 0
|
||||||
|
m = a^b
|
||||||
|
while m:
|
||||||
|
count +=1
|
||||||
|
m = m & (m-1)
|
||||||
|
return count
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
def count_bits_swap(a, b):
|
||||||
|
m = a^b
|
||||||
|
return count_1s(m)
|
||||||
|
|
||||||
|
|
||||||
|
def count_1s(m):
|
||||||
|
count = 0
|
||||||
|
while m:
|
||||||
|
if m& 1 :
|
||||||
|
count +=1
|
||||||
|
m >>= 1
|
||||||
|
return count
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
a = int('10010000', 2)
|
||||||
|
b = int('01011010', 2)
|
||||||
|
print count_bits_swap(a, b) #4
|
||||||
|
print count_bits_swap2(a, b) #4
|
26
First_edition_2014/ebook_src/bitwise/set_bit.py
Executable file
26
First_edition_2014/ebook_src/bitwise/set_bit.py
Executable file
@ -0,0 +1,26 @@
|
|||||||
|
#!/usr/bin/env python
|
||||||
|
|
||||||
|
__author__ = "bt3"
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
''' Set a bit in a binary number:
|
||||||
|
1) Shifts 1 over by i bits
|
||||||
|
2) make an OR with the number, only the value at bit i will change and all the others bit
|
||||||
|
of the mask are zero so will not affect the num
|
||||||
|
'''
|
||||||
|
|
||||||
|
|
||||||
|
def set_bit(num, i):
|
||||||
|
mask = 1 << i
|
||||||
|
return bin( num | mask )
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
num = int('0100100', 2)
|
||||||
|
print set_bit(num, 0) #'0b100101'
|
||||||
|
print set_bit(num, 1) #'0b100110'
|
||||||
|
print set_bit(num, 2) # nothing change '0b100100'
|
||||||
|
print set_bit(num, 3) #'0b101100'
|
||||||
|
print set_bit(num, 4) #'0b110100'
|
||||||
|
print set_bit(num, 5) # nothing change '0b100100'
|
23
First_edition_2014/ebook_src/bitwise/swap_in_place.py
Executable file
23
First_edition_2014/ebook_src/bitwise/swap_in_place.py
Executable file
@ -0,0 +1,23 @@
|
|||||||
|
#!/usr/bin/env python
|
||||||
|
|
||||||
|
__author__ = "bt3"
|
||||||
|
|
||||||
|
'''
|
||||||
|
swapping values in place without extra memory
|
||||||
|
'''
|
||||||
|
|
||||||
|
|
||||||
|
def swap_bit(a, b):
|
||||||
|
'''
|
||||||
|
>>> swap_bit(14, 73)
|
||||||
|
(73, 14)
|
||||||
|
'''
|
||||||
|
a = a^b
|
||||||
|
b = a^b
|
||||||
|
a = a^b
|
||||||
|
return a, b
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
import doctest
|
||||||
|
doctest.testmod()
|
37
First_edition_2014/ebook_src/bitwise/swap_odd_even.py
Executable file
37
First_edition_2014/ebook_src/bitwise/swap_odd_even.py
Executable file
@ -0,0 +1,37 @@
|
|||||||
|
#!/usr/bin/env python
|
||||||
|
|
||||||
|
__author__ = "bt3"
|
||||||
|
|
||||||
|
|
||||||
|
''' Swap odd and even bits in a smart way in a binary:
|
||||||
|
1) first for odds, take n and move the odd:
|
||||||
|
(a) Mask all odd bits with 10101010 (0xAA)
|
||||||
|
(b) shift by right by 1
|
||||||
|
2) do the same to ints with 01010101
|
||||||
|
3) merge
|
||||||
|
'''
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
def swap_odd_even(num):
|
||||||
|
'''
|
||||||
|
>>> num = 0b11011101
|
||||||
|
>>> result = '0b1101110'
|
||||||
|
>>> swap_odd_even(num) == result
|
||||||
|
True
|
||||||
|
'''
|
||||||
|
|
||||||
|
mask_odd = 0xAA # 0b10101010
|
||||||
|
mask_even = 0x55 # 0b1010101
|
||||||
|
odd = num & mask_odd
|
||||||
|
odd >>= 1
|
||||||
|
even = num & mask_even
|
||||||
|
even >>= 1
|
||||||
|
return bin(odd | even)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
import doctest
|
||||||
|
doctest.testmod()
|
||||||
|
|
22
First_edition_2014/ebook_src/bitwise/update_bit.py
Executable file
22
First_edition_2014/ebook_src/bitwise/update_bit.py
Executable file
@ -0,0 +1,22 @@
|
|||||||
|
#!/usr/bin/env python
|
||||||
|
|
||||||
|
__author__ = "bt3"
|
||||||
|
|
||||||
|
''' This method merges set bit and clean bit:
|
||||||
|
1) first clear the bit at i using a mask such as 1110111
|
||||||
|
2) then shift the intended value v by i bits
|
||||||
|
3) this will create a number with bit i to v and all other to 0
|
||||||
|
4) finally update the ith bit with or
|
||||||
|
'''
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
def update_bit(num, i, v):
|
||||||
|
mask = ~ (1 << i)
|
||||||
|
return bin( (num & mask) | (v << i) )
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
num = int('10010000', 2)
|
||||||
|
print update_bit(num, 2, 1) # '0b10010100'
|
||||||
|
|
0
First_edition_2014/ebook_src/builtin_structures/__init__.py
Executable file
0
First_edition_2014/ebook_src/builtin_structures/__init__.py
Executable file
51
First_edition_2014/ebook_src/builtin_structures/anagram.py
Executable file
51
First_edition_2014/ebook_src/builtin_structures/anagram.py
Executable file
@ -0,0 +1,51 @@
|
|||||||
|
#!/usr/bin/env python
|
||||||
|
|
||||||
|
__author__ = "bt3"
|
||||||
|
|
||||||
|
|
||||||
|
from collections import Counter
|
||||||
|
|
||||||
|
def is_anagram(s1, s2):
|
||||||
|
'''
|
||||||
|
>>> is_anagram('cat', 'tac')
|
||||||
|
True
|
||||||
|
>>> is_anagram('cat', 'hat')
|
||||||
|
False
|
||||||
|
'''
|
||||||
|
counter = Counter()
|
||||||
|
for c in s1:
|
||||||
|
counter[c] += 1
|
||||||
|
|
||||||
|
for c in s2:
|
||||||
|
counter[c] -= 1
|
||||||
|
|
||||||
|
for i in counter.values():
|
||||||
|
if i:
|
||||||
|
return False
|
||||||
|
|
||||||
|
return True
|
||||||
|
|
||||||
|
''' verify if words are anagrams by comparing a sum of Unicode code
|
||||||
|
point of the character'''
|
||||||
|
|
||||||
|
def get_unicode_sum(word):
|
||||||
|
s = 0
|
||||||
|
for p in word:
|
||||||
|
s += ord(p)
|
||||||
|
return s
|
||||||
|
|
||||||
|
|
||||||
|
def is_anagram2(word1, word2):
|
||||||
|
'''
|
||||||
|
>>> is_anagram2('cat', 'tac')
|
||||||
|
True
|
||||||
|
>>> is_anagram2('cat', 'hat')
|
||||||
|
False
|
||||||
|
'''
|
||||||
|
return get_unicode_sum(word1) == get_unicode_sum(word2)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
import doctest
|
||||||
|
doctest.testmod()
|
||||||
|
|
9
First_edition_2014/ebook_src/builtin_structures/balance.txt
Executable file
9
First_edition_2014/ebook_src/builtin_structures/balance.txt
Executable file
@ -0,0 +1,9 @@
|
|||||||
|
__author__ = "bt3"
|
||||||
|
|
||||||
|
|
||||||
|
This is the classic "you have 8 balls/coins, which are the same weight, except for one which is slightly heavier than the others. You also have an old-style balance. What is the fewest number of weighings to find the heavy coin/ball?
|
||||||
|
|
||||||
|
Answer: 2! You need to use every information available:
|
||||||
|
Weight 3 x 3 balls/coins.
|
||||||
|
If they weight the same: weight the 2 balls/coins left outside.
|
||||||
|
Else, measure 2 of the 3 heavier balls/coins.
|
40
First_edition_2014/ebook_src/builtin_structures/balance_symbols.py
Executable file
40
First_edition_2014/ebook_src/builtin_structures/balance_symbols.py
Executable file
@ -0,0 +1,40 @@
|
|||||||
|
#!/usr/bin/env python
|
||||||
|
|
||||||
|
__author__ = "bt3"
|
||||||
|
|
||||||
|
'''
|
||||||
|
Given a N different open and close braces in a string "( { [ } ] )".
|
||||||
|
How do you check whether the string has matching braces.
|
||||||
|
'''
|
||||||
|
|
||||||
|
from collections import Counter
|
||||||
|
def check_if_balance(string):
|
||||||
|
'''
|
||||||
|
>>> check_if_balance('{[[(])}]')
|
||||||
|
True
|
||||||
|
>>> check_if_balance('{[[()}]')
|
||||||
|
False
|
||||||
|
>>> check_if_balance('')
|
||||||
|
True
|
||||||
|
'''
|
||||||
|
table = Counter()
|
||||||
|
for i in string:
|
||||||
|
|
||||||
|
index = str(ord(i))[0]
|
||||||
|
if i in '{[(':
|
||||||
|
table[index] += 1
|
||||||
|
|
||||||
|
elif i in ')}]':
|
||||||
|
table[index] -= 1
|
||||||
|
|
||||||
|
for i in table.values():
|
||||||
|
if i !=-0:
|
||||||
|
return False
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
import doctest
|
||||||
|
doctest.testmod()
|
||||||
|
|
@ -0,0 +1,71 @@
|
|||||||
|
#!/usr/bin/env python
|
||||||
|
|
||||||
|
__author__ = "bt3"
|
||||||
|
|
||||||
|
"""
|
||||||
|
Given an integer x and an unsorted array of integers, describe an
|
||||||
|
algorithm to determine whether two of the numbers add up to x.
|
||||||
|
|
||||||
|
1. Using hash tables.
|
||||||
|
2. Sorting the array and keeping two pointers in the array, one in
|
||||||
|
the beginning and one in the end. Whenever the sum of the current
|
||||||
|
two integers is less than x, move the first pointer forwards, and
|
||||||
|
whenever the sum is greater than x, move the second pointer
|
||||||
|
backwards. O(nln n).
|
||||||
|
3. Create a BST with x minus each element in the array.
|
||||||
|
Check whether any element of the array appears in the BST.
|
||||||
|
It takes O(nlog n) times two.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from collections import defaultdict, Counter
|
||||||
|
|
||||||
|
def check_sum(array, k):
|
||||||
|
'''
|
||||||
|
>>> check_sum([3, 2, 6, 7, 9, 1], 8)
|
||||||
|
[(6, 2), (1, 7)]
|
||||||
|
>>> check_sum([5, 2, 6, 7, 9, 1], 4)
|
||||||
|
[]
|
||||||
|
>>>
|
||||||
|
'''
|
||||||
|
|
||||||
|
dict = defaultdict()
|
||||||
|
res = []
|
||||||
|
|
||||||
|
for i in array:
|
||||||
|
if k-i in dict:
|
||||||
|
res.append((i, k-i))
|
||||||
|
del dict[k-i]
|
||||||
|
else:
|
||||||
|
dict[i] = 1
|
||||||
|
|
||||||
|
return res
|
||||||
|
|
||||||
|
|
||||||
|
def check_sum2(array, k):
|
||||||
|
'''
|
||||||
|
>>> check_sum2([1, 4, 2, 7, 1, 3, 10, 15, 3, 1], 6)
|
||||||
|
set([(3, 3)])
|
||||||
|
>>> check_sum2([1, 4, 2, 7, 1, 3, 10, 15, 3, 1], 0)
|
||||||
|
set([])
|
||||||
|
'''
|
||||||
|
|
||||||
|
dict = Counter()
|
||||||
|
res = set()
|
||||||
|
|
||||||
|
for i in array:
|
||||||
|
dict[i] += 1
|
||||||
|
|
||||||
|
for i in array:
|
||||||
|
if dict[k-i] > 0:
|
||||||
|
if i == k-i and dict[k-i] > 1:
|
||||||
|
res.add((i, k-i))
|
||||||
|
dict[k-i] -= 2
|
||||||
|
elif i == k-i:
|
||||||
|
res.add((i, k-i))
|
||||||
|
dict[k-i] -= 1
|
||||||
|
|
||||||
|
return res
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
import doctest
|
||||||
|
doctest.testmod()
|
@ -0,0 +1,36 @@
|
|||||||
|
#!/usr/bin/env python
|
||||||
|
|
||||||
|
__author__ = "bt3"
|
||||||
|
|
||||||
|
|
||||||
|
''' Determine if an Array of integers contains 3 numbers that sum to 0 '''
|
||||||
|
|
||||||
|
from collections import defaultdict
|
||||||
|
|
||||||
|
def find_3_number(array):
|
||||||
|
'''
|
||||||
|
>>> find_3_number([1,5,56,11,-3,-12])
|
||||||
|
1 11 -12
|
||||||
|
True
|
||||||
|
>>> find_3_number([] )
|
||||||
|
False
|
||||||
|
'''
|
||||||
|
hash_ = defaultdict()
|
||||||
|
for i in array:
|
||||||
|
hash_[i] = 1
|
||||||
|
|
||||||
|
for i, x in enumerate(array):
|
||||||
|
for y in array[i+1:]:
|
||||||
|
if -(x+y) in hash_:
|
||||||
|
print x, y, -(x+y)
|
||||||
|
return True
|
||||||
|
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
import doctest
|
||||||
|
doctest.testmod()
|
||||||
|
|
@ -0,0 +1,35 @@
|
|||||||
|
#!/usr/bin/env python
|
||||||
|
|
||||||
|
__author__ = "bt3"
|
||||||
|
|
||||||
|
|
||||||
|
'''
|
||||||
|
given an array of intervals, return max number of non-overlapping intervals
|
||||||
|
'''
|
||||||
|
|
||||||
|
from collections import defaultdict
|
||||||
|
|
||||||
|
def non_overlapping(array):
|
||||||
|
'''
|
||||||
|
>>> non_overlapping([(1,2), (2,5), (1, 6)])
|
||||||
|
[[(1, 2), (2, 5)]]
|
||||||
|
>>> non_overlapping([(1,4), (2,5), (3, 6)])
|
||||||
|
[]
|
||||||
|
'''
|
||||||
|
total = []
|
||||||
|
|
||||||
|
for i, t in enumerate(array):
|
||||||
|
start = t[0]
|
||||||
|
end = t[1]
|
||||||
|
for tt in array[i+1:] :
|
||||||
|
if end <= tt[0]:
|
||||||
|
total.append([(start, end), (tt[0], tt[1])])
|
||||||
|
|
||||||
|
return total
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
import doctest
|
||||||
|
doctest.testmod()
|
||||||
|
|
64
First_edition_2014/ebook_src/builtin_structures/convert_numerical_bases.py
Executable file
64
First_edition_2014/ebook_src/builtin_structures/convert_numerical_bases.py
Executable file
@ -0,0 +1,64 @@
|
|||||||
|
#!/usr/bin/env python
|
||||||
|
|
||||||
|
__author__ = "bt3"
|
||||||
|
|
||||||
|
''' convert an integer to a string in any base'''
|
||||||
|
|
||||||
|
def convert_from_dec_to_any_base(number, base):
|
||||||
|
'''
|
||||||
|
>>> number, base = 9, 2
|
||||||
|
>>> convert_from_dec_to_any_base(number, base)
|
||||||
|
'1001'
|
||||||
|
'''
|
||||||
|
|
||||||
|
convertString = '012345679ABCDEF'
|
||||||
|
|
||||||
|
if number < base:
|
||||||
|
return convertString[number]
|
||||||
|
|
||||||
|
else:
|
||||||
|
return convert_from_dec_to_any_base(number//base, base) + \
|
||||||
|
convertString[number%base]
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
def convert_from_decimal_to_binary(number, base):
|
||||||
|
'''
|
||||||
|
>>> number, base = 9, 2
|
||||||
|
>>> convert_from_decimal_to_binary(number, base)
|
||||||
|
1001
|
||||||
|
'''
|
||||||
|
|
||||||
|
multiplier, result = 1, 0
|
||||||
|
|
||||||
|
while number > 0:
|
||||||
|
result += number%base*multiplier
|
||||||
|
multiplier *= 10
|
||||||
|
number = number//base
|
||||||
|
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
def convert_from_decimal_larger_bases(number, base):
|
||||||
|
'''
|
||||||
|
>>> number, base = 31, 16
|
||||||
|
>>> convert_from_decimal_larger_bases(number, base)
|
||||||
|
'1F'
|
||||||
|
'''
|
||||||
|
strings = "0123456789ABCDEFGHIJ"
|
||||||
|
result = ""
|
||||||
|
|
||||||
|
while number > 0:
|
||||||
|
digit = number%base
|
||||||
|
result = strings[digit] + result
|
||||||
|
number = number//base
|
||||||
|
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
import doctest
|
||||||
|
doctest.testmod()
|
||||||
|
|
83
First_edition_2014/ebook_src/builtin_structures/convert_str_2_int.py
Executable file
83
First_edition_2014/ebook_src/builtin_structures/convert_str_2_int.py
Executable file
@ -0,0 +1,83 @@
|
|||||||
|
#!/usr/bin/env python
|
||||||
|
|
||||||
|
__author__ = "bt3"
|
||||||
|
|
||||||
|
|
||||||
|
def conv_int2str(int1):
|
||||||
|
'''
|
||||||
|
>>> conv_str2int('367')
|
||||||
|
367
|
||||||
|
>>> conv_str2int('0')
|
||||||
|
0
|
||||||
|
>>> conv_str2int('-10')
|
||||||
|
-10
|
||||||
|
>>> conv_str2int('1e5')
|
||||||
|
100000
|
||||||
|
'''
|
||||||
|
|
||||||
|
aux_dict = {key:value for key in range(10) for value in '0123456789'[key]}
|
||||||
|
|
||||||
|
if int1 == 0:
|
||||||
|
return '0'
|
||||||
|
elif int1 < 0:
|
||||||
|
sign = '-'
|
||||||
|
int1 = int1*(-1)
|
||||||
|
else:
|
||||||
|
sign = ''
|
||||||
|
|
||||||
|
|
||||||
|
aux_ls = []
|
||||||
|
|
||||||
|
while int1 > 0:
|
||||||
|
c = int1%10
|
||||||
|
int1 = int1//10
|
||||||
|
cadd = aux_dict[c]
|
||||||
|
aux_ls.append(cadd)
|
||||||
|
|
||||||
|
aux_ls.reverse()
|
||||||
|
|
||||||
|
return sign + ''.join(aux_ls)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
def conv_str2int(str1):
|
||||||
|
'''
|
||||||
|
>>> conv_int2str(0)
|
||||||
|
'0'
|
||||||
|
>>> conv_int2str(1e5)
|
||||||
|
'100000'
|
||||||
|
>>> conv_int2str(367)
|
||||||
|
'367'
|
||||||
|
>>> conv_int2str(-10)
|
||||||
|
'-10'
|
||||||
|
'''
|
||||||
|
if not str1:
|
||||||
|
return None
|
||||||
|
|
||||||
|
aux_dict = {key:value for value in range(10) for key in '0123456789'[value]}
|
||||||
|
|
||||||
|
if str1[0] == '-':
|
||||||
|
sign = -1
|
||||||
|
str1 = str1[1:]
|
||||||
|
else:
|
||||||
|
sign = 1
|
||||||
|
|
||||||
|
dec, result = 1, 0
|
||||||
|
|
||||||
|
for i in range(len(str1)-1, -1, -1):
|
||||||
|
aux = str1[i]
|
||||||
|
if aux == 'e':
|
||||||
|
exp_num = conv_str2int(str1[i+1:])
|
||||||
|
number = conv_str2int(str1[:i])
|
||||||
|
result = number*10**exp_num
|
||||||
|
break
|
||||||
|
result += aux_dict[aux]*dec
|
||||||
|
dec *= 10
|
||||||
|
|
||||||
|
return result*sign
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
import doctest
|
||||||
|
doctest.testmod()
|
||||||
|
|
26
First_edition_2014/ebook_src/builtin_structures/count_unique_words_On2.py
Executable file
26
First_edition_2014/ebook_src/builtin_structures/count_unique_words_On2.py
Executable file
@ -0,0 +1,26 @@
|
|||||||
|
#!/usr/bin/env python
|
||||||
|
|
||||||
|
__author__ = "bt3"
|
||||||
|
|
||||||
|
import collections
|
||||||
|
import string
|
||||||
|
import sys
|
||||||
|
|
||||||
|
|
||||||
|
def count_unique_word():
|
||||||
|
|
||||||
|
words = collections.defaultdict(int)
|
||||||
|
|
||||||
|
strip = string.whitespace + string.punctuation + string.digits + "\"'"
|
||||||
|
|
||||||
|
for filename in sys.argv[1:]:
|
||||||
|
with open(filename) as file:
|
||||||
|
for line in file:
|
||||||
|
for word in line.lower().split():
|
||||||
|
word = word.strip(strip)
|
||||||
|
if len(word) > 2:
|
||||||
|
words[word] = +1
|
||||||
|
|
||||||
|
for word in sorted(words):
|
||||||
|
print("'{0}' occurs {1} times.".format(word, words[word]))
|
||||||
|
|
49
First_edition_2014/ebook_src/builtin_structures/delete_duplicate_char_str.py
Executable file
49
First_edition_2014/ebook_src/builtin_structures/delete_duplicate_char_str.py
Executable file
@ -0,0 +1,49 @@
|
|||||||
|
#!/usr/bin/env python
|
||||||
|
|
||||||
|
__author__ = "bt3"
|
||||||
|
|
||||||
|
''' find and delete all the duplicate characters in a string '''
|
||||||
|
|
||||||
|
from collections import Counter
|
||||||
|
|
||||||
|
def delete_unique(str1):
|
||||||
|
'''
|
||||||
|
>>> delete_unique("Trust no one")
|
||||||
|
'on'
|
||||||
|
>>> delete_unique("Mulder?")
|
||||||
|
''
|
||||||
|
'''
|
||||||
|
|
||||||
|
str_strip = ''.join(str1.split())
|
||||||
|
repeat = Counter()
|
||||||
|
|
||||||
|
for c in str_strip:
|
||||||
|
repeat[c] += 1
|
||||||
|
|
||||||
|
result = ''
|
||||||
|
for c, count in repeat.items():
|
||||||
|
if count > 1:
|
||||||
|
result += c
|
||||||
|
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
def removing_duplicates_seq(str1):
|
||||||
|
'''
|
||||||
|
>>> delete_unique("Trust no one")
|
||||||
|
'on'
|
||||||
|
>>> delete_unique("Mulder?")
|
||||||
|
''
|
||||||
|
'''
|
||||||
|
seq = str1.split()
|
||||||
|
result = set()
|
||||||
|
for item in seq:
|
||||||
|
if item not in result:
|
||||||
|
#yield item
|
||||||
|
result.add(item)
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
import doctest
|
||||||
|
doctest.testmod()
|
60
First_edition_2014/ebook_src/builtin_structures/fibonacci.py
Executable file
60
First_edition_2014/ebook_src/builtin_structures/fibonacci.py
Executable file
@ -0,0 +1,60 @@
|
|||||||
|
#!/usr/bin/env python
|
||||||
|
|
||||||
|
__author__ = "bt3"
|
||||||
|
|
||||||
|
|
||||||
|
def fib_generator():
|
||||||
|
a, b = 0, 1
|
||||||
|
|
||||||
|
while True:
|
||||||
|
yield b
|
||||||
|
a, b = b, a+b
|
||||||
|
|
||||||
|
|
||||||
|
def fib(n):
|
||||||
|
'''
|
||||||
|
>>> fib(2)
|
||||||
|
1
|
||||||
|
>>> fib(5)
|
||||||
|
5
|
||||||
|
>>> fib(7)
|
||||||
|
13
|
||||||
|
'''
|
||||||
|
if n < 3:
|
||||||
|
return 1
|
||||||
|
|
||||||
|
a, b = 0, 1
|
||||||
|
count = 1
|
||||||
|
|
||||||
|
while count < n:
|
||||||
|
count += 1
|
||||||
|
a, b = b, a+b
|
||||||
|
|
||||||
|
return b
|
||||||
|
|
||||||
|
|
||||||
|
def fib_rec(n):
|
||||||
|
'''
|
||||||
|
>>> fib_rec(2)
|
||||||
|
1
|
||||||
|
>>> fib_rec(5)
|
||||||
|
5
|
||||||
|
>>> fib_rec(7)
|
||||||
|
13
|
||||||
|
'''
|
||||||
|
if n < 3:
|
||||||
|
return 1
|
||||||
|
return fib_rec(n - 1) + fib_rec(n - 2)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
import doctest
|
||||||
|
doctest.testmod()
|
||||||
|
|
||||||
|
fib = fib_generator()
|
||||||
|
print(next(fib))
|
||||||
|
print(next(fib))
|
||||||
|
print(next(fib))
|
||||||
|
print(next(fib))
|
@ -0,0 +1,35 @@
|
|||||||
|
#!/usr/bin/env python
|
||||||
|
|
||||||
|
__author__ = "bt3"
|
||||||
|
|
||||||
|
|
||||||
|
def find_0_MxN(m):
|
||||||
|
''' find 0s in a matrix and replace the col and row to 0s:
|
||||||
|
>>> m1 = [[1,2,3,4], [5,6,7,8], [9,10,11,12], [13,14,15,16]]
|
||||||
|
>>> find_0_MxN(m1)
|
||||||
|
[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]
|
||||||
|
>>> m2 = [[1, 2, 3, 4], [0, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]
|
||||||
|
>>> find_0_MxN(m2)
|
||||||
|
[[0, 2, 3, 4], [0, 0, 0, 0], [0, 10, 11, 12], [0, 14, 15, 16]]
|
||||||
|
'''
|
||||||
|
index = []
|
||||||
|
|
||||||
|
for row in range(len(m)):
|
||||||
|
for col in range(len(m[0])):
|
||||||
|
if m[row][col] == 0:
|
||||||
|
index.append((row, col))
|
||||||
|
for i in index:
|
||||||
|
row = i[0]
|
||||||
|
col = i[1]
|
||||||
|
for i in range(len(m)):
|
||||||
|
m[row][i] = 0
|
||||||
|
for i in range(len(m[0])):
|
||||||
|
m[i][col] = 0
|
||||||
|
|
||||||
|
return m
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
import doctest
|
||||||
|
doctest.testmod()
|
||||||
|
|
32
First_edition_2014/ebook_src/builtin_structures/find_dice_probabilities.py
Executable file
32
First_edition_2014/ebook_src/builtin_structures/find_dice_probabilities.py
Executable file
@ -0,0 +1,32 @@
|
|||||||
|
#!/usr/bin/env python
|
||||||
|
|
||||||
|
__author__ = "bt3"
|
||||||
|
|
||||||
|
'''
|
||||||
|
given 2 dice, determine number of ways to sum S if all dice are rolled
|
||||||
|
'''
|
||||||
|
|
||||||
|
from collections import Counter, defaultdict
|
||||||
|
|
||||||
|
def find_dice_probabilities(S=5, n_faces=6):
|
||||||
|
if S > 2*n_faces or S < 2:
|
||||||
|
return None
|
||||||
|
|
||||||
|
cdict = Counter()
|
||||||
|
ddict = defaultdict(list)
|
||||||
|
|
||||||
|
for dice1 in range(1, n_faces+1):
|
||||||
|
for dice2 in range(1, n_faces+1):
|
||||||
|
t = [dice1, dice2]
|
||||||
|
cdict[dice1+dice2] += 1
|
||||||
|
ddict[dice1+dice2].append( t)
|
||||||
|
|
||||||
|
return [cdict[S], ddict[S]]
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
results = find_dice_probabilities()
|
||||||
|
assert(results[0] == len(results[1]))
|
43
First_edition_2014/ebook_src/builtin_structures/find_edit_distance.py
Executable file
43
First_edition_2014/ebook_src/builtin_structures/find_edit_distance.py
Executable file
@ -0,0 +1,43 @@
|
|||||||
|
#!/usr/bin/env python
|
||||||
|
|
||||||
|
__author__ = "bt3"
|
||||||
|
|
||||||
|
|
||||||
|
''' computes the edit distance between two strings '''
|
||||||
|
|
||||||
|
|
||||||
|
def find_edit_distance(str1, str2):
|
||||||
|
'''
|
||||||
|
>>> s = 'sunday'
|
||||||
|
>>> t = 'saturday'
|
||||||
|
>>> find_edit_distance(s, t)
|
||||||
|
3
|
||||||
|
'''
|
||||||
|
|
||||||
|
m = len(str1)
|
||||||
|
n = len(str2)
|
||||||
|
diff = lambda c1, c2: 0 if c1 == c2 else 1
|
||||||
|
|
||||||
|
E = [[0] * (n + 1) for i in range(m + 1)]
|
||||||
|
|
||||||
|
for i in range(m + 1):
|
||||||
|
E[i][0] = i
|
||||||
|
|
||||||
|
for j in range(1, n + 1):
|
||||||
|
E[0][j] = j
|
||||||
|
|
||||||
|
for i in range(1, m + 1):
|
||||||
|
for j in range(1, n + 1):
|
||||||
|
E[i][j] = min(E[i-1][j] + 1, E[i][j-1] + 1, E[i-1][j-1] + diff(str1[i-1], str2[j-1]))
|
||||||
|
|
||||||
|
return E[m][n]
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
import doctest
|
||||||
|
doctest.testmod()
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
x
Reference in New Issue
Block a user