- Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathstructures.py
More file actions
Latest commit
119 lines (99 loc) · 2.23 KB
/
Copy pathstructures.py
File metadata and controls
119 lines (99 loc) · 2.23 KB
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
# study some high-level data structures in python
# ref: http://blog.jobbole.com/65218/
importcollectionsascl
importarray
importheapq
importbisect
importweakref
importpprint
### collections
# Counter
# count the number of times an element occurs
deftest_counter():
li= ["Dog", "Cat", "Mouse", 42, "Dog", 42, "Cat", "Dog"]
a=cl.Counter(li)
printa
printa.most_common(2)
# Deque
deftest_deque():
q=cl.deque(range(5))
printq
q.append(13)
q.appendleft(22)
printq
printq.pop()
printq.popleft()
printq
q.rotate(2)
printq
# Defaultdict
# Same with dict, except when a key not exists
deftest_defaultdict():
s="the quick brown fox jumps over the lazy dog"
words=s.split()
l=cl.defaultdict(list)
fork,vinenumerate(words):
l[v].append(k)
printl
d= {}
fork,vinenumerate(words):
d.setdefault(k,[]).append(v)
printd
# same with counter
li= ["Dog", "Cat", "Mouse", 42, "Dog", 42, "Cat", "Dog"]
dd=cl.defaultdict(int)
forkinli:
dd[k] +=1
printdd
### Array: small than list, element with one type
# i is type code, stands for signed int
deftest_array():
a=array.array('i',range(5))
printa
b=array.array(a.typecode,[x*2forxina])
printb
fori,xinenumerate(a):
a[i] =x*2
printa
### heapq
deftest_heapq():
heap= []
forvinrange(5):
heapq.heappush(heap,v)
printheapq.heappop(heap)
printheapq.nlargest(3,heap)
### bisect
deftest_bisect():
a= [1,2,6,89]
bisect.insort_right(a,4)
printa
printbisect.bisect(a,3)
### weakref
# like = , strong ref. except destroyed only when none ref is left
# do not really understand yet!
deftest_weakref():
a=2
b=a
delb
printa
classFoo():
a=1
f=Foo()
d=weakref.ref(f)
delf
printd
### pprint
# beautiful print
deftest_pprint():
matrix= [ [1,2,3], [4,5,6], [7,8,9] ]
a=pprint.PrettyPrinter(width=20)
a.pprint(matrix)
if__name__=='__main__':
# test_counter()
# test_deque()
# test_defaultdict()
# test_array()
# test_heapq()
# test_bisect()
# test_weakref()
test_pprint()