Black Mamba

Faster, Higher, Stronger.

Python Notes V

Python Version Binary Search

1
2
3
4
5
6
7
8
9
10
11
12
def search2Binary(seq, num, lower=0, upper=None):
    if upper is None:
        upper = len(seq) - 1
    if lower == upper:
        assert(num == seq[upper])
        return upper
    else:
        mid = (upper + lower) // 2
        if num > seq[mid]:
            return search2Binary(seq, num, mid + 1, upper)
        else:
            return search2Binary(seq, num, lower, mid)

Throwing Functions Around

  • map() Applies the function to all the elements in the sequences
1
2
map(str, range(3)) # Equivalent to [str(i) for i in range(3)
['0', '1', '2', '3']
  • filter() Returns a list of those elements for which the function is true
1
2
3
4
5
6
7
8
9
10
def func(x):
    return x.isalnum()

seq = ["foo", "x41", "?!", "***"]
filter(func, seq)
['foo', 'x41']

# another way
[x for x in seq if x.isalnum()]
['foo', 'x41']
  • lambda
1
2
filter(lambda x: x.isalnum(), seq)
['foo', 'x41']
  • reduce() Equivalent to func(func(func(seq[0], seq[1]), seq[2]), …)
1
2
3
numbers = [75, 101, 13, 100]
reduce(lambda x, y: x+y, numbers)
288

Python STL

  • Set
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
set(range(5))
{0, 1, 2, 3, 4}

set([1, 2, 6, 4, 6, 2, 4,  3, 3])
{1, 2, 3, 4, 6}

a = set([1, 2, 3])
b = set([2, 3, 4])

a.union(b)
{1, 2, 3, 4}

a | b
{1, 2, 3, 4}

a & b
{2, 3}

c = a & b
c.issubset(a)
True

a > c
True

a.intersection(b)
{2, 3}
>>> a.difference(b)
{1}
a - b
{1}

a.symmetric_difference(b)
{1, 4}

a ^ b
{1, 4}

a.copy()
{1, 2, 3}

a.copy is a
False
  • Heap
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
from heapq import *
from random import shuffle

data = range(10)
shuffle(data)
data
[7, 2, 1, 9, 3, 4, 5, 6, 8, 0]

heap = []
for n in data:
    heappush(heap, n)

heap
[0, 1, 2, 6, 3, 4, 5, 9, 8, 7]

# heappush(heap, value), heappop(heap), heapify(heap)
heappush(heap, 0.5)
heap
[0, 0.5, 2, 6, 1, 4, 5, 9, 8, 7, 3]

# heappop(heap)
heappop(heap)
0
heappop(heap)
0.5
heap
[1, 3, 2, 6, 7, 4, 5, 9, 8]

# heapify(heap)
heap = [3, 2, 5, 9, 4, 8, 7, 1, 6]
heapify(heap)
heap
[1, 2, 5, 3, 4, 8, 7, 9, 6]

# heapreplace()
heapreplace(heap, 0.5)
1

heap
[0.5, 2, 5, 3, 4, 8, 7, 9, 6]

heapreplace(heap, 10)
0.5

heap
[2, 3, 5, 6, 4, 8, 7, 9, 10]
  • Deque
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
from collections import deque

# append(), appendleft()
q = deque(range(5))
q.append(5)
q.appendleft(6)
q
deque([6, 0, 1, 2, 3, 4, 5])

# pop(), popleft()
q.pop()
5
q.popleft()
6
q
deque([0, 1, 2, 3, 4])

# rotate(), shift to right
q.rotate(3)
q
([2, 3, 4, 0, 1])
q.rotate(1)
q
deque([1, 2, 3, 4, 0])
q.rotate(-1)
q
deque([2, 3, 4, 0, 1])
  • time
1
2
time.asctime()
'Fri May  2 13:32:20 2015'
  • random
1
2
3
# generate number from [0, n)
n = 6
randrange(n)
  • re
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import re
text= 'alpha, beta,,,,gamma   delta'
re.split('[, ]+', text)
['alpha', 'beta', 'gamma', 'delta']

# maxsplit indicates the max number of splits allowed
re.split('[, ]+', text, maxsplit=2)
['alpha', 'beta', 'gamma   delta']
re.split('[, ]+', text, maxsplit=1)
['alpha', 'beta,,,,gamma   delta']

pat = '[a-zA-Z]+'
text = '"Hm... Err -- are you sure?" he said, sounding insecure.'

re.findall(pat, text)
['Hm', 'Err', 'are', 'you', 'sure', 'he', 'said', 'sounding', 'insecure']

sng = r'[.?\",]+'
re.findall(sng, text)
['"', '...', '?"', ',', '.']
  • sub(origin, ‘text’, substitute)
1
2
3
4
origin = ' '
substi = 'Hello, '
re.sub(origin, 'Peter', substi)
'Hello,Peter'
  • escape()

    Used to scape all the characters in a string that might be interpreted as a regular expression operator. If there is a long string with lots of special characters and escape() can help avoid typing a lot of backslashes.

1
2
3
4
re.escape('www.python.org')
'www\\.python\\.org'
re.escape('Today is a good day.')
'Today\\ is\\ a\\ good\\ day\\.'
  • match()
1
2
3
4
5
6
7
8
9
10
11
12
m = re.match(r'www\.(.*)\..{3}', 'www.python.org')
m.group(1)
'python'
m.start(1)
4
m.end(1)
10
m.span(1)
(4, 10)

m.group(0)
'www.python.org'

Python Database

  • Sqlite
1
2
3
4
5
6
7
8
import sqlite3
conn = sqlite3.connect('somedatabase.db')

# get the cursor from the connection
cur = conn.cursor()

conn.commit()
conn.close()

Tools for Testing

  • doctest
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# my_math.py
def mySquare(x):
'''
Square a number and returns the result.

mySquare(2)
4
mySquare(3)
9
'''
    return x * x

# add the lollowing code at the bottom
if __name__ == '__main__':
    import doctest, my_math
    doctest.testmod(my_math)

Then, run the testmod and watch the script

1
2
$ python my_math.py
$ python my_math.py -v

The test output:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
Trying:
    mySquare(2)
Expecting:
    4
ok
Trying:
    mySquare(3)
Expecting:
    9
ok
1 items had no tests:
    my_math
1 items passed all tests:
    2 tests in my_math.mySquare
2 tests in 2 items.
2 passed and 0 failed.
Test passed.
  • unittest
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# my_math.py
def product(x, y):
    return x*y

# test_my_math.py
import unittest, my_math

class ProductTestCase(unittest.TestCase):

    def testIntegers(self):
        for x in range(-10, 10):
            for y in range(-10, 10):
                p = my_math.product(x, y)
                self.failUnless(p == x*y, 'Integer failed')

    def testFloat(self):
        for x in range(-10, 10):
            for y in range(-10, 10):
                x = x/10.0
                y = y/10.0
                p = my_math.product(x, y)
                self.failUnless(p == x*y, 'Float failed')

# add the lollowing code at the bottom
if __name__ == '__main__': unittest.main()

Then, type F5 To run test_my_math.py

1
2
3
4
5
..
---------------------------------------------------
Ran 2 tests in 0.050s

OK

Comments