-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpython_practice.py
More file actions
537 lines (405 loc) · 12.6 KB
/
python_practice.py
File metadata and controls
537 lines (405 loc) · 12.6 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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
# ==================== Binary Search Review ====================
# def checkForNum(arr, num):
# lo, hi = 0, len(arr)-1
# while lo <= hi:
# mid = (lo + hi) // 2
# if num == arr[mid]:
# return True
# elif num > arr[mid]:
# lo = mid + 1
# else:
# hi = mid - 1
# return False
# print(checkForNum([1,2,3,4,5], 2.5))
# ==================== Number Conversion ====================
# def addStrings(str1, str2):
# def makeNum(s):
# num, dec, div = 0, 0, 1
# isDec = False
# for c in s:
# if c == '.':
# isDec = True
# continue
# if not isDec:
# num = num * 10 + ord(c) - ord('0')
# else:
# dec = dec * 10 + ord(c) - ord('0')
# div *= 10
# if div > 1:
# dec /= div
# return num + dec
# s1 = makeNum(str1)
# s2 = makeNum(str2)
# return str(s1+s2).strip('.0')
# print('addStrings', addStrings('10000000000000000000000000000001', '10000000000000000000000000000001'))
# print(bin(int('0b11', 2) + int('0b11', 2)))
# x = 46
# x = hex(x)
# print(x)
# y = int(x, base=16)
# print(y)
# ==================== Slicing ====================
# x = ['a', 'b', 'c', 'd', 'e']
# print(x[0:])
# print(x[0::])
# print(x[0::1])
# # IMPORTANT -- a positive 'step' without an explicit start implicitly sets the start to 0,
# # where a negative 'step' without an explicit start implicitly sets the start to -1
# print(x[::2])
# print(x[::-1])
# print(x[::-2])
# ==================== Merge Sort (again!) ====================
# def merge(arr1, arr2):
# merged = []
# i = j = 0
# while i < len(arr1) and j < len(arr2):
# if arr1[i] < arr2[j]:
# merged.append(arr1[i])
# i += 1
# else:
# merged.append(arr2[j])
# j += 1
# merged += arr1[i:] if i < len(arr1) else arr2[j:]
# return merged
# def mergeSort(arr):
# if len(arr) <= 1:
# return arr
# l = len(arr) // 2
# return merge(mergeSort(arr[:l]), mergeSort(arr[l:]))
# print(mergeSort([5,4,3,2,1]))
# ==================== bisect module ====================
# import bisect
# x = [1,2,3,3,5]
# print(bisect.bisect(x, 5))
# ==================== working with set copies and scope ====================
# def test(se):
# print(se)
# se = se.copy()
# se.add(4)
# print(se)
# x = {1,2,3}
# print('o', x)
# test(x)
# print('o', x)
# ==================== str.maketrans() and str.translate ====================
# x = 'abcba'
# # y = x.maketrans('ab', '12')
# y = x.maketrans({'a': None, 'b': None})
# y = x.maketrans('ab', 'mn')
# print(y)
# z = x.translate(y)
# print(z)
# ==================== any() and all() built-ins ====================
# iterators = [5,5]
# while all(i > 0 for i in iterators):
# print('all while loop', iterators)
# iterators[0] -= 1
# iterators = [5,5]
# while any(i > 0 for i in iterators):
# print('any while loop', iterators)
# iterators[0] -= 1
# iterators[1] -= 2
# print(i > 0 for i in [5,5])
# print(any(i>0 for i in [0,0]))
# print(all([5==5,5==6]))
# print(any([5==5,5==6]))
# print([5==5, 5==6])
# print(all([5, 6, 7]))
# print(all([0, 0, 0]))
# ==================== Dynamic Programming / Memoization ====================
# calcs = [0]
# cache = {}
# def fib(n):
# calcs[0] += 1
# if n in cache:
# return cache[n]
# if n < 2:
# cache[n] = n
# return n
# cache[n] = fib(n-1) + fib(n-2)
# return cache[n]
# print(fib(30))
# print(calcs)
# ==================== Graphs + BFS/DFS ====================
# from collections import deque
# # Implemented as Adjacency List
# class Graph:
# def __init__(self):
# self.numberOfNodes = 0
# self.adjacencyList = {}
# def addVertex(self, node):
# self.adjacencyList[node] = []
# self.numberOfNodes += 1
# return self
# def addEdge(self, node1, node2):
# # Undirected
# self.adjacencyList[node1].append(node2)
# self.adjacencyList[node2].append(node1)
# return self
# def breadthFirstSearch(self, ver):
# visited = {key: False for key in self.adjacencyList}
# ans, queue = [], deque([ver])
# visited[ver] = True
# while queue:
# ver = queue.popleft()
# ans.append(ver)
# for neighbor in self.adjacencyList[ver]:
# if visited[neighbor] == False:
# queue.append(neighbor)
# visited[neighbor] = True
# return ans
# def depthFirstSearch(self, ver):
# visited = {key: False for key in self.adjacencyList}
# ans = []
# visited[ver] = True
# def goDeeper(ver):
# for neighbor in self.adjacencyList[ver]:
# if visited[neighbor] == False:
# visited[neighbor] = True
# goDeeper(neighbor)
# ans.append(ver)
# goDeeper(ver)
# return ans
# def showConnections(self):
# return self
# myGraph = Graph()
# myGraph.addVertex(0)
# myGraph.addVertex(1)
# myGraph.addVertex(2)
# myGraph.addVertex(3)
# myGraph.addEdge(0, 1)
# myGraph.addEdge(0, 2)
# myGraph.addEdge(1, 2)
# myGraph.addEdge(2, 3)
# print(myGraph.adjacencyList)
# print(myGraph.breadthFirstSearch(next(iter(myGraph.adjacencyList))))
# print(myGraph.depthFirstSearch(next(iter(myGraph.adjacencyList))))
# ==================== Recursion ====================
# def factorial(num):
# if num == 1:
# return num
# return factorial(num - 1) * num
# print(factorial(5))
# def func(num):
# num -= 1
# if num == 0:
# return [0]
# res = []
# for i in range (1,num,2):
# for j in func(i):
# print('in func loop', "j", j)
# # for k in func(num - i):
# root = [1]
# root += [['left', j]]
# res += root
# return res
# print(func(5))
# ==================== Collections - Counter module ====================
# from collections import Counter
# c = Counter({'f':1, 'e':6})
# print(c)
# d = Counter('fleeeeeeeeergh')
# c.update(['g','w','w'])
# print(c - d)
# print(c)
# lis = [99, 44, 6, 2, 1, 5, 63, 87, 283, 4, 88]
# i, p = 0, len(lis)-1
# while p > i:
# if lis[i] > lis[p]:
# lis[i], lis[p], lis[p-1] = lis[p-1], lis[i], lis[p]
# p -= 1
# else:
# i += 1
# print(lis)
# ==================== Heap Practice ====================
# =============== heapq module ===============
# import heapq as h
# k = 2
# lis = [2,5,4,7,8,9,3,4]
# h.heapify(lis)
# print(lis)
# for i in range(k-1):
# h.heappop(lis)
# print(lis[0])
# =============== Attempt at implementing my own max-heap ===============
# class MinHeap:
# def __init__(self):
# self.lis = [0]
# self.size = 0
# def insertVal(self, val):
# self.lis.append(val)
# self.size += 1
# self.percUp(self.size)
# def percUp(self, i):
# while i // 2 > 0 and self.lis[i] < self.lis[i // 2]:
# self.lis[i], self.lis[i // 2] = self.lis[i // 2], self.lis[i]
# i //= 2
# def percDown(self, i):
# return
# def findVal(self, val):
# return 0
# def delVal(self, val):
# i = self.findVal(val)
# self.lis[i] = self.lis.pop()
# if i * 2 < self.size and self.lis[i] > self.lis[i * 2]:
# self.percDown(i)
# elif i * 2 + 1 < self.size and self.lis[i] > self.lis[i * 2 + 1]:
# self.percDown(i)
# elif i // 2 > 0 and self.lis[i] < self.lis[i // 2]:
# self.percUp(i)
# ==================== Sorting Practice ====================
# =============== Quick Sort ===============
# Holy shitnit I did it!
# def quickSort(lis, piv):
# if len(lis) == 1:
# return lis
# def pivot(lis, p):
# i = 0
# while p > i:
# if lis[i] > lis[p]:
# lis[i], lis[p], lis[p-1] = lis[p-1], lis[i], lis[p]
# p -= 1
# else:
# i += 1
# if i == 0:
# return lis[:i+1], lis[i+1:]
# return lis[:i], lis[i:]
# lf, rt = pivot(lis, piv)
# print("lf", lf, "rt", rt)
# left = quickSort(lf, len(lf)-1)
# right = quickSort(rt, len(rt)-1)
# return left + right
# nums = [99, 44, 6, 2, 1, 5, 63, 87, 283, 4, 0]
# print(quickSort(nums, len(nums)-1))
# =============== Merge Sort ===============
# def mergeSort(lis):
# if len(lis) == 1:
# return lis
# left = lis[:len(lis) // 2]
# right = lis[len(lis) // 2:]
# def merge(left, right):
# lf_i, rt_i, comb = 0, 0, []
# while lf_i < len(left) and rt_i < len(right):
# if left[lf_i] < right[rt_i]:
# comb += [left[lf_i]]
# lf_i += 1
# else:
# comb += [right[rt_i]]
# rt_i += 1
# comb += right[rt_i:] if lf_i == len(left) else left[lf_i:]
# return comb
# return merge(mergeSort(left), mergeSort(right))
# print(mergeSort([2,5,4,1,7,3,4,2]))
# =============== Insertion Sort ===============
# def insertionSort(lis):
# for i in range(len(lis)-1):
# if lis[i] > lis[i+1]:
# temp = lis[i+1]
# for j in range(i+1, -1, -1):
# if lis[j-1] > temp and j-1 > -1:
# lis[j] = lis[j-1]
# else:
# lis[j] = temp
# break
# insertionSort([85,12,59,45,72,51])
# ==================== RegEx Practice ====================
# import re
# x = re.compile(r'[a-zA-Z_]+@[\w]+.[\w]+')
# y = x.match('farts@flernch.com')
# print(y)
# ==================== Mutibility and Immutibility ====================
# lis = [1,2,3]
# dic = {1:'A', 2:'B', 3:'C'}
# se = {'A', 'B', 'C'}
# tup = (5, "Hello", [1,2,3], dic)
# num = 5
# st = "Hello"
# boo = True
# fset = frozenset({1, 2, 3})
# def testFunc(lis, dic, se, tup, num, st, boo, fset):
# # lis[0] = 4
# # dic[1] = 'D'
# se -= {'A'}
# # print(f"def lis ({id(lis)}):",lis)
# # print(f"def dic ({id(dic)}):", dic)
# print(f"def se ({id(se)}):", se)
# tup[2].append(456)
# num += 6
# st += ', Worldo'
# boo = False
# fset -= {1}
# print(f"def tup ({id(tup)}):", tup)
# print(f"def num ({id(num)}):", num)
# print(f"def st ({id(st)}):", st)
# print(f"def boo ({id(boo)}):", boo)
# print(f"def fset ({id(fset)}):", fset)
# return
# testFunc(lis, dic, se, tup, num, st, boo, fset)
# # print(f"outside lis ({id(lis)}):",lis)
# # print(f"outside dic ({id(dic)}):", dic)
# print(f"outside se ({id(se)}):", se)
# num += 7
# st += ', Worldd'
# print(f"outside tup ({id(tup)}):", tup)
# print(f"outside num ({id(num)}):", num)
# print(f"outside st ({id(st)}):", st)
# print(f"outside boo ({id(boo)}):", boo)
# print(f"outside fset ({id(fset)}):", fset)
# ==================== Classes + Inheritance Practice ====================
# class Stacker:
# def __init__(self):
# self.stacker = []
# self.index = -1
# def addSomeShit(self, val):
# self.stacker.append(val)
# return self
# def __iter__(self):
# return self
# def __next__(self):
# if self.index == len(self.stacker)-1:
# raise StopIteration
# self.index = self.index + 1
# return self.stacker[self.index]
# class TestMe(Stacker):
# def __init__(self):
# super().__init__()
# def addSomeShit(self, val):
# super().addSomeShit(val)
# return self.stacker
# tester = TestMe()
# tester.addSomeShit(99)
# tester.addSomeShit(84)
# tester.addSomeShit(47)
# print("tester", tester.stacker)
# print("tester", tester)
# poops = Stacker()
# poops.addSomeShit(5)
# poops.addSomeShit(7)
# poops.addSomeShit(9)
# print("poops", poops.stacker)
# buttiter = iter(poops)
# for val in buttiter:
# print("forloop", val)
# print(buttiter)
# print(buttiter.__next__())
# print(buttiter.__next__())
# print(buttiter.__next__())
# print(buttiter.__next__())
# ==================== Exception Handling Practice ====================
# try:
# butts
# print(butts)
# except NameError as poops:
# print("NameError:", poops)
# print("eat my farts")
# raise
# finally:
# print("eat more of my farts")
# x = 1
# if x < 2:
# raise Exception(f"eat all the farts, don't go over {x}")
# butts
# print(butts)
# ==================== Strings ====================
# word = "Python"
# print(word.lower())