-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNotes.py
2300 lines (1838 loc) · 78.6 KB
/
Notes.py
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
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
date(2019,7,20) - Originally Started with Python2, then migrated to python3 via 2to3-3.7 tool. Possible py2->3 bugs.
--------------------
Python 2.7 Quickref sheet:
http://www.astro.up.pt/~sousasag/Python_For_Astronomers/Python_qr.pdf
Good References:
https://www.geeksforgeeks.org/python-programming-language/
Practice:
https://www.hackerrank.com
https://practice.geeksforgeeks.org/
https://leetcode.com/problems/two-sum/
Data Structures Snippets.
https://www.tutorialspoint.com/python/python_data_structure.htm
- Arrays, Lists, Dictionaries, Tuples, Matrix, Sets
- Linked Lists, Queue, Dequeue, HAshTable, Binary Tree, Search, Heaps, Graphs, algo..
"""
from functools import reduce
def Wisdom():
"""
Double, Triple, check question input/constraint/output.
- Re-word in your code as comments before solving after reading the full question. Ensure code meets those objectives.
- You often miss-read/assume during first read due to not having read the later part.
e.g: "The maximum length of the extension is 3", Means *Up to 3*, not exactly 3.
Testing:
- Before submission, always check the broken test case.
- Before submission, test with a bunch of test cases. [working,broken,corner cases]
- Usually best to implement a function and test against some custom granular inupt, rather than test a full stdin
This makes it easier to write mini-testing frameworks for when a problem can have many little corner cases.
E.g hackerrank_problem_Regex__Validate_email_address
Here instead of hard-coding logic that does everything in a single function, we break the function that
validates emails into a separate function.
We then test this a small test framework against many different email addresses.
- It's a good idea to implement a little testing framework if input can have many corner cases.
Mistakes I tend to make:
- Regex:
- Forget to make it an exact match. ^...$ See:regex_pattern_exact_match
- Use match instead of search.
- Syntax:
a == b # instead of a = b
- Data Structures:
- Try to use the logically 'correct' datastructure for each job. Don't try to hack it with anohter one.
- E.g: if you need a Stack, use a stack (list). If you need a queue use a deque.
Try not to use a stack(list) as a dequeue item and hacking by adding/poping items in reverse as this leads
to subtle bugs.
See problem: Trees__top_view
Indexing:
- I make mistakes if I use arra[index] for nodes/edges.
Sol: -> append i to index values. E.g nodei edgei
- Label offsets if you use multiple times to avoid typos/errors.
Efficient algorithms:
- If it's a tough algo:
try to write dumb/naive algo,
generate lots of random tests,
test new algo against olg algo with random tests. E.g: hackerrank_DataStructures_Stacks__LargestRect
Note about Recursion:
- Not efficient in python, but if can't solve iterarativley, increase recursion limit. sys.setrecursionlimit(100000)
- Converting iterative to recursion is not systematic, each algo requires thuoght.
- I found that sometimes recursion simplifies solution a lot.
e.g Graph problem (and maybe backgtracking/dynamic problems):
https://www.quora.com/How-often-is-recursion-brought-up-in-coding-interviews-at-larger-companies-like-Google-Facebook-Amazon-etc
Approaching large & complex problems: (hours/days kinda problems)
- First implement the naive and ineffective solution & get it working. E.g implement recursively or via a O(n^2) algo.
This ensures that you have a good grasp on the problem.
You should be quick enough to code things via simple/naive solution.
- Implement unit tests.
- Then optimize solution (or parts of solution) as you go along and validate via unit tests.
Often it's much easier to build the more efficient solution if you have a working naive solution.
"""
def whiteboarding():
"""
- To try:
[] Problem: Need to move segments of code.
Try: Work landscape, main function has sub-function calls.
Try: Think further ahead, keep code in mind. Try scrap code & expand after.
"""
pass
pass
def notations_short_hands_for_examples():
pass
_ = None
n = 123
L = [1,2,3,4]
S = set([1,2,3])
D = dict()
def Py2vs3():
def division():
# Division Produces floats
# 2: 5 / 2 = 2
# 3: 5 / 2 = 2.5 -> 5 // 2 = 2
pass
# [10,4, 2, 1, 5]
# [40,100,200, ]
#
# [5,10,3 ] 18-3
# [13,8,15]
def unicode():
# Unicode
# 2: str is bytes (ascii)
# 3: str is unicode
pass
def range_map_filter():
# 2: xrange = iter, range = list
# 3: xrange doesn't exist. range = iter.
# map -> iter alt: use: [func(x) for x in list]
# filter -> iter
# p2 x = filter(lambda x : x % 2 == 0, [1,2,3,4]) #-> [2, 4]
# p3 x = list(filter(lambda x: x % 2 == 0, [1,2,3,4]))
# ++ x = [x for x in [1,2,3,4] if x % 2 == 0] #-> [2,4]
# dictonary's .keys(), .values(), .items() -> iter (yay)
# reduce -> Na. Moved to: 'from functools import reduce'. & returns list still.
pass
def tool_2to3():
# there is a 2to3 (and 2to3-7) tool to automatically port py2 to py3.
pass
def input_func():
# 2: X = raw_input ("enter some values)
# 3: X = input ("enter some values")
# 3-> X = eval(input("expr)")
pass
def print_func():
# 2: print "hello" # sys.stdout.write("stuff")
# 3: print("msg", [end=""])
pass
def sorting():
# todo -research a bit more:
pass
# builtin.sorted() and list.sort() no longer accept the cmp argument providing a comparison function.
# Use the key argument instead. N.B. the key and reverse arguments are now “keyword-only”.
#
# The cmp() function should be treated as gone, and the __cmp__() special method is no longer supported.
# Use __lt__() for sorting, __eq__() with __hash__(), and other rich comparisons as needed.
# (If you really need the cmp() functionality, you could use the expression (a > b) - (a < b) as the equivalent for cmp(a, b).)
# https://docs.python.org/3/whatsnew/3.0.html
############# NEW in python 3:
def set_dict_comprehension():
s = {i for i in range(10)} # -> {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
d = {k: v for k, v in [[1, 'val1'], [2, 'val2']]} # -> {1: 'val1', 2: 'val2'}
# Refs
# https://docs.python.org/3/whatsnew/3.0.html Overview ref.
# https://python-future.org/compatible_idioms.html Cheatsheet
def typing():
# Cheatsheet: https://mypy.readthedocs.io/en/latest/cheat_sheet_py3.html
pass
def print_func():
print("Hello")
print("Hello", "World!") #-> 'Hello World!' # no new line, but with a space.
# Printing multi-Lines:
print("Hello\nWorld")
# Hello
# World
print(["Hello\nWorld"]) # Putting multiline strings into a list prints them on a single line. Shows special chars.
['Hello\nWorld']
# Handle new-line manually:
import sys
sys.stdout.write(str(123)) # write a string w/o newline and w/o space. https://www.hackerrank.com/challenges/python-print/problem
# alternative is to use __future__ and python 3's prting with print("geeks", end =""), see https://www.geeksforgeeks.org/print-without-newline-python/
# Alternative, construct a string (" ".joint(iterable)) & print on single line
# You can use python3's print function if:
#from __future__ import print_function # is first line in script.
#print("End2", end='')
def function_example(a, b, myarg="default_value*1"): #LTAG__default_arguments_paramaters
print((a + b))
# call: function_example(2, 4, myarg=bob)
# [1] Note, default value is static across all function calls. See: gotcha_default_args_evaluated_only_once()
# Note, default values are evaluated only once, so if dealing with objects
# it can introduce bugs. See: gotcha_default_args_evaluated_only_once
outside_var = "helloworld"
def func_nesting():
print(outside_var) # Can access outside var.
# outside_var = "goodbye world" # ERROR. Python2: Cannot re-bind outside variable. Use dic: d["x"] = val.
# Ref: https://stackoverflow.com/questions/3190706/nonlocal-keyword-in-python-2-x
def multiple_return_values():
a, b = 1, 2 # comma separated. Returns tuple, can auto-unzip it.
def Branching():
def if_elif_else():
# Selection
# if (bool_expr):
# stmt ...
# [elif (bool_expr):
# stmt
# [else:
# stmt
pass
def single_line_if():
if True: return "end" # works on single line, but not recommended as per pep8.
# src: https://stackoverflow.com/questions/18669836/is-it-possible-to-write-single-line-return-statement-with-if-statement
def tenary_if():
a, b = 5, 2
min = a if a < b else b #https://www.geeksforgeeks.org/ternary-operator-in-python/
print(("bob" if 1 == 2 else "jack"))
def member_in_list():
if 2 in [1, 2, 3]:
print ("2 is in 1,2,3")
def boolean_logic():
# not and or # words rather than signs
# (EXPR) op (EXPR) # Brackets can be deeply nested.
if (not (False or (True and True))) or True:
print(True)
# Morgan:
# Boolen: not (A or B) == not A and not B # Mnemonic: not -> A == Not a. not-> or == and.
# not (A and B) == not A or not B
# Set : not (A | B) == not A & not B
# not (A & B) == not A | not B
def primitive_datatypes():
# int, 32 bit 10
# long Intiger > 32bits 10L
# float 10.0
# complex 1.2j
# bool True, False
# str "mystr"
# tuple (immutable sequence) (2,4,7)
# list (mutable sequence) [2,x,3.1]
# dict (Mapping) {x:2, y:2}
pass
def math_ops():
# a OP b, OP in +, -, *, **, %, >, <=, >=, !=, ==
# Note fractions:
4 / 3 # Py3: 1.33 Py2: 1
4.0 / 3.0 # = 1.3333 # float division float(4) / float(3)r
4.0 // 3.0 # = 1.0 # integer division
# print (10.0 / 4.0) # = 2.5
# print (2 ** 3) # = 8 (exponential, to power of)
# print (11 % 5) # = 1 (mod)
def incrementing():
# You can't i++, instead:
i = 0
i += 1 # ref: https://stackoverflow.com/questions/2632677/python-integer-incrementing-with/2632687#2632687
def fractions():
from fractions import Fraction
f = Fraction(10, 5) # Fraction(2, 1)
# f = f1 OP f2 OP + * etc..
f.numerator
f.denominator
f.conjugate()
# Ref: https://docs.python.org/2/library/fractions.html
# Getting median value from a sorted array
from math import ceil, floor
def median(L):
if len(L) % 2 == 1:
med_i = ((len(L) + 1) / 2) - 1
return L[int(med_i)]
else:
med_i = ((len(L) + 1.0) / 2.0) - 1
left = int(floor(med_i))
right = int(ceil(med_i))
return (L[left] + L[right]) / 2.0
# Test:
for i in [1, 2, 3, 4, 5]:
L = list(range(i))
med = median(L)
print(L, med)
def Loops():
# (for | while) can contain (break | continue)
def while_loop():
while True:
print("infLoop")
pass
def for_loops():
# for VAR in <ITERABLE>:
# stmt
for i in [1, 2, 3, 4]:
print((i * i))
def for_loop_reverse():
# To traverse a list in reverse, can use negative range
L = [1, 2, 3, 4]
for i in range(len(L) - 1, -1, -1):
print(L[i])
def for_loop_with_else():
# "else" part in a for loop is executed if a break never occured. As a "last" entry.
mystr = "helloMoto123"
for s in mystr:
if s.isdigit():
print(s)
break
else:
print("no digit found")
# -> 1
def for_enumerate():
for i, w in enumerate(['a', 'b', 'c'], 1): # starting at 1 instead of 0
print(i, w)
# 0 a
# 1 b
# 2 c
def while_else_break():
# When to use 'else' in a while loop?
# Else is executed if while loop did not break.
# I kinda like to think of it with a 'runner' metaphor.
# The "else" is like crossing the finish line, irrelevant of whether you started at the beginning or end of the track. "else" is only not executed if you break somewhere in between.
runner_at = 0 # or 10 makes no difference, if unlucky_sector is not 0-10
unlucky_sector = 6
while runner_at < 10:
print("Runner at: ", runner_at)
if runner_at == unlucky_sector:
print("Runner fell and broke his foot. Will not reach finish.")
break
runner_at += 1
else:
print("Runner has finished the race!") # Not executed if runner broke his foot.
# ref: https://stackoverflow.com/questions/3295938/else-clause-on-python-while-statement/57247169#57247169
# E.g breaking out of a nested while ≤loop # LTAG
for i in [1, 2, 3]:
for j in ['a', 'unlucky', 'c']:
print(i, j)
if j == 'unlucky':
break
else:
continue # Only executed if inner loop didn't break.
break # This is only reached if inner loop 'breaked' out since continue didn't run.
print("Finished")
# 1 a
# 1 unlucky
# Finished
def lambda_map_filter_reduce() :
numbers = [1, 2, 3, 4]
# Lambda Map
double = lambda x: x + x
numbers_doubled = list(map(double, numbers)) # -> [2, 4, 6, 8]
# Problem: https://www.hackerrank.com/challenges/map-and-lambda-expression/problem
# Pass lambda around to functions
def pass_lambda(lambdaFunc, i):
return lambdaFunc(i)
print(pass_lambda(lambda x: x + 1, 1))
# Lambda filter
keep_even = lambda x: x % 2 == 0
numbers_filtered = list(filter(keep_even, numbers)) # ref: https://stackabuse.com/lambda-functions-in-python/
# Reduce
# Concept: Reduce to a single value. Cumulatively in succession, left to right, reduce.
# In python 3, reduce needs to be imported.
reduce(lambda x, y: x + y, [1, 2, 3]) #->6
reduce(lambda x, y: x + y, [1, 2, 3], -1) # -> 5 # default value.
class String_Theory:
def string_comparison(self):
"leo" == "leo" # Equality. Preferred.
"leo" is "leo" # identity. id("leo"). Work, but equality generally preffered.
# https://stackoverflow.com/questions/2988017/string-comparison-in-python-is-vs
def string_multiline(self):
# -) For multi-line strings, indentation is as-is. Yon can use '\' for early line breaks thou.
ml = """\
line
hello
world\
"""
# -) Or manually join:
var = ("implicitly\n"
"Joined\n"
"string\n")
# ref: https://stackoverflow.com/questions/2504411/proper-indentation-for-python-multiline-strings
def string_splicing(self):
myString = "RedHat"
# Menonic: str[from:till)
myString[1:] # edHat
myString[:2] # Re
myString[0] # R #index starts at 0?
def spring_splitting(self):
# Splitting & Joining:
# Note: Delimiter matters. By default, spaces are removed.
# "A B".split() #-> ["A","B"]
# "A B".split(" ") #-> ["A", "", "", "B"]
mystr = "hello world how are you"
mySplitStrList = mystr.split(" ") # delimiter. -> ["hello", "world" ...
concatinated_by_delimiter = "-".join(mySplitStrList) # -> "hello-world-how-.... #ref: https://www.programiz.com/python-programming/methods/string/join
# See also re.split()
def string_reversal(self):
"leo"[::-1] #-> "ih" #reverser string #anki-todo
# ==
"".join(reversed(list("leo")))
def raw_strings(self):
# prefix 'r' to ignore escape sequences.
print("hello\nworld")
#hello
#world
print(r"hello\nworld")
#hello\nworld
# \n new line \<STUFF> is hazardous.
# \t tab
# \\ backslash
# \' \"
# ref: https://docs.python.org/2.0/ref/strings.html
def string_concatination(self):
# " ".join(..) has effective run-time. http://blog.mclemon.io/python-efficient-string-concatenation-in-python-2016-edition
# delimiter.join([str1,str2,str3])
" ".join(["hello", "world", "war", "Z"]) #'hello world war Z'
"".join(["hello ", "world ", "war ", "Z"]) #'hello world war Z'
" ".join(map(str, [1,2,3])) # useful to print data structures.
# For building some pretty output, consider
self.string_formatting(self)
def string_formatting(self):
# 2 methods:
# - .format() >= python 2.6. Better support for native Data structures (dict etc..) use for new code.
# - % == Old C-Printf style. Discouraged due to quirky behaviour but not deprecated.
# Manual or Automatic field numbering:
"Welcome {} {}!".format("Bob", "Young")
# "{arg_index} | {arg_name}".format([args])
"{0} {0} {1} {2} {named}".format("hello", "world", 99, named="NamedArg")
'hello hello world 99 NamedArg'
# (!) DANGER: padding with None can throw.
"{}".format(None) # OK.
"{:<5}".format(None) # (!) Throws TypeError: unsupported format string passed to NoneType.__format__
"{:<5}".format(str(None)) # OK
# Padding: # {: Filler_Char | > | ^ | < NUMS}
"{:>10}".format("Hello") # {:>10} Pad Right 10 Note {:XX} == {:>XX}
' Hello'
"{:<10}".format("Hello") # {:<10} Pad Left 10
'Hello '
"{:_>10}".format("Hello") # Pad with character.
'_____Hello'
"{:_^10}".format("Hello") # Center Align.
'__Hello___'
# Truncating ".len" like str[:2]
"{:.2}".format("Hello")
'He'
# Numbers:
"Number:{:d}".format(42) # d = int. f = float.
'Number:42'
# Numbers: Float, truncate last digits
"{:.1f}".format(1.134) #-> 1.1
# Numbers with padding: (min, but prints full number if len(str) > min)
"Lucky Number:{:3d}".format(42)
'Lucky Number: 42'
"{:<10.2f}".format(233.146) # Truncate by 2 and pad 10. {
'233.15 '
# For signs & signs + padding, see ref 1.
# Dictionary
d = {"leo": 31, "bob": 55}
"{d[bob]} {d[leo]}".format(d=d)
'55 31'
# List
"{l[0]} {l[1]}".format(l=['a','b'])
'a b'
# Parametrized Format:
"{:{padding}.{truncate}f}".format(3.14632, padding=10, truncate=2)
' 3.15'
# Also: DateTime formatting 1* class *1
# Refs:
# [1] Lots of examples: https://pyformat.info/
# [1] Which String Formatting method to use?: https://realpython.com/python-string-formatting
def string_update_char(self):
# Strings are immutable. To update one:
mystr = "absde"
# 1) Turn into a list. Manipulate list.
strlist = list(mystr)
strlist[2] = "c"
mystr2 = "".join(strlist)
print(mystr2)
# Src: https://stackoverflow.com/questions/19926089/python-equivalent-of-java-stringbuffer
# ExProb: https://www.hackerrank.com/challenges/swap-case/problem
# 2) Slice
mystr3 = mystr[:2] + "c" + mystr[3:]
print(mystr3)
#lref_pystr_index Anki-x # HackerR: https://www.hackerrank.com/challenges/python-mutations/problem
def string_validation(self):
"a-z,A-Z,0-9".isalnum() # Alpha Numeric. (!= regex '\w')
"a-Z".isalpha() # Alphabetical. # Not quite the same as regex '\w' since \w contains '_'
"123".isdigit()
"a-z123".islower()
"ABC123".isupper()
# Example problem: https://www.hackerrank.com/challenges/string-validators/problem
def string_constants____kwds_lower_upper_letters_alphabet(self):
import string
string.ascii_lowercase
# 'abcdefghijklmnopqrstuvwxyz'
string.ascii_uppercase
# 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
string.ascii_letters
# 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
def string_alinghment(self):
"Leo".ljust(20, "#")
#'Leo#################'
"Leo".center(20, "#")
#'########Leo#########'
"Leo".rjust(20, "#")
#'#################Leo'
#ex: https://www.hackerrank.com/challenges/text-alignment/problem
#ex: https://www.hackerrank.com/challenges/designer-door-mat/problem
def string_wrapping(self):
import textwrap
print(textwrap.wrap("HelloWorld", 5))
#Hello
#World
def string_stripping(self):
"00005".lstrip("0") # 5
"50000".rstrip("0") # 5
def string_numerical_values____kwds_unicode(self):
ord('a') # 97 # return unicode value. #ascii being subset of unicode.
chr(97) # 'a' input: [0 ... 255]
chr(97) #u'a' input: [0 ... 65535] anki-done (
# ref: https://www.geeksforgeeks.org/ord-function-python/
# prob: https://www.hac5535kerrank.com/challenges/most-commons/problem
def string_substring_counting(self):
# Count substring
":-| ^_^ :-) -_- :-) *_* :-)".count(":-)") #3
"aaaa".count("a", 1, 3) # 2 [start]/[end]
def string_index_of_a_letter(self):
"abcd".index("b") # 1
def every_substring(s): # e.g abba -> ['a', 'b'...,'bba', 'abba']
ss = []
for l in range(1, len(s) + 1): # l = 1..4
for i in range(0, len(s) - l + 1): # l=1 -> i=(0, 4-1+1-1=3)
ss.append(s[i:i + l]) # e.g 0:1 > a 0:2 -> ab # for generator: yield s[i:i+l]
return ss
print(every_substring("abba")) # ['a', 'b', 'b', 'a', 'ab', 'bb', 'ba', 'abb', 'bba', 'abba']
n = len("abba")
substring_count = (n * (n + 1)) // 2
def List_():
L = [1, 4, 2, 1, 2, "A"] # [] for empty list.
# Append:
L.append(99)
L += ["abc"] # Note, += <Iterable>. if you += "abc" you get ["a","b","c"] rather than ["abc].
# Note1: += [i] is 2x slower than .append()
# Insert:
L.insert(0, 5) # insert 5 at start of list.
# Index:
L[0] # first element
L[-1] # last element
L[-3] # 3rd last.
# Remove
L.remove(5)
# Pop (read & remove from right).
L.pop()
# Ref: https://www.geeksforgeeks.org/python-list/
# List has .count() function to count # of items inside it:
[1, 1, 5].count(1)
#2
# Empty list is False. 1+ is True.
L = []
if not L:
print("List is empty.")
# Useful if you want to set default value in functions if function did not do anything with list.
# L2 = L or ["default]
def multi_dimensional_lists():
# List of lists..
L = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
L[0][1]
#2
def deduplicating_list():
uniquearr = list(dict.fromkeys(L)) #anki-todo
uniquearr.sort(reverse=True)
print(uniquearr)
def list_comprehension():
# Single level
nums = [1, 2, 3, 4, 5, 6]
double_evens = [n * 2 for n in nums if n % 2 == 0]
print("Single level ", double_evens) # [4, 8, 12]
# Nested
first_list = [2, 4, 6]
second_list = [1, 2, 3]
product_first_second = [a * b for a in first_list for b in second_list] # "if a EXPR b" filter possible.
print("Nested", product_first_second) # [2, 4, 6, 4, 8, 12, 6, 12, 18]
# First loop, 2nd 3rd
indent_list_a = [1, 2, 3]
indent_list_b = [10, 20, 30]
added_list = [a + b
for a in indent_list_a
for b in indent_list_b
if a % 2 != 0] # [11, 21, 31, 13, 23, 33]
print("Multi-Line", added_list)
# Practice Problem: https://www.hackerrank.com/challenges/list-comprehensions/problem
# Reference: https://hackernoon.com/list-comprehension-in-python-8895a785550b
def mapping_func_to_iter():
# map (func, iter1 [, iter 2]) # function has 1 arg per iter.
numbers = (1, 2, 3, 4)
result = [x + x for x in numbers] # apply function (or lamdba) to an iterable item. RETURN: list
print((list(result)))
# src: https://www.geeksforgeeks.org/python-map-function/
# See src for multi-arg, string looping etc..
def bisect_insert_sorted(): # TAG__List TAG__Insertion TAG__Sorted binary insert
# Useful to insert an element such that list stays sorted.
# Bisect is O(log n), but insertion is O(n).
from bisect import insort
L = [1, 3]
insort(L, 2)
#L == [1, 2, 3]
def bisect_bisect():
from bisect import bisect
# Bisect gives position of where to insert item. (i+1)
L = [1, 3, 5, 7]
to_ins = 4
L.insert(bisect(L, to_ins), to_ins)
# [1, 3, 4, 5, 7]
def generator_expressions():
# Create generator to iterate over. (yieling_func)
gen = (i * 2 for i in range(10))
for i in gen:
print(i)
# 1 2 3 ..
# src: https://dbader.org/blog/python-generator-expressions
L = list(range(10))
L_iter = (-L[i] for i in range(len(L)))
for i in L_iter:
print(i)
# 0, -1, -2, -3 ....
def sorting(): # 828a4bad40234324ba24bd02f6595334 -> CheatSheet.
L = [2, 1, 3]
# Opt 1) In-Place:
# myList.sort([key=lambda x: EXPR][, reverse=False]):
L.sort()
# Prob: https://www.hackerrank.com/challenges/python-sort-sort/problem
# Opt 2) Return a new sorted list:
# sorted(<Iterable>, [key=lambda x: EXPR], [reverse=False])
# new_sorted_list = sorted([obj1,obj2,obj3], [key=lambda x: x.attribute], reverse=True)
# Dealing with situation where you need to sort an on index
L = [[2,"a"], [1, "b"]]
L.sort(key=lambda x:x[0]) # -> [[1, 'b'], [2, 'a']] # sort by number at index 0.
L.sort(key=lambda x:x[1]) # -> [[2, 'a'], [1, 'b']] # sort by number at index 1
# ref: https://docs.python.org/2/library/functions.html#sorted
# Note: in-place sort can't sort string. sorted(s) can. To sort a string:
"".join(sorted("bac")) # anki-todo
def dict_examples():
mydic = {'jack': 999, 'jennie': 111}
mydic['leo'] = 123
mydic['bob'] = 234
mydic['leo'] # accessing
mydic.pop('bob') # deleting
print(mydic)
# src: https://www.geeksforgeeks.org/python-dictionary/
# See also OrderedDict in collections.
def set_examples():
L = [1,2,3]
B = [2,3,4]
# set is an undordered collection of items.
# To modify an item, remove(item) & add(item).
myset = set() # ref: https://www.geeksforgeeks.org/python-sets/
myset = set([1,2,3])
myset = {8,9}
myset.add(1)
myset.add(2)
myset.add(3)
myset.update([1,2,3]) # #like add for a list.
myset.intersection_update(set()) # Modifies myset.
myset.difference_update(set())
myset.symmetric_difference_update(set())
myset.discard(999) # works even if e not in set.
myset.remove(2) # Raises KeyError if e doesn't exist.
myset.pop() # Raises KeyError if e doesn't exist.
if 2 in myset:
print("2 is in set!")
len(myset)
# Return new sets:
# Set Theory:
setA, setB = set(), set()
setA.union(setB) #(A | B) -> returns new set...
setA.intersection(setB) # (A & B) # ref: https://www.programiz.com/python-programming/set
setA.difference(setB) # (A - B) # values that exist in A but not in B.
setA.symmetric_difference(setB) # (A ^ B) # in either a or b, but not both.
# Diagrams: https://www.hackerrank.com/challenges/py-set-symmetric-difference-operation/problem
# setA.issubset(t) s <= b
# setA.issuperset(t) s >= b
# ref: https://docs.python.org/2/library/sets.html
def heaps_with_heapq():
# 1ed485d0f6614735afbf9a7efc834caf
# Methods that take an Array as arguments:
from heapq import heapify, heappush, heappop, heapreplace
heap = []
heapify(list) # augments the list. O(n)
heappush(heap, int) # O(log n)
heappop(int) # O(log n)
heap[0] # peak.
# heapq is a min heap.
# For max heap, negate input & output "heappush(h, -val)" "-heappop(h)"
# Small classes to wrap min/max heaps are good/clean way to deal with heaps.
class maxheap:
def __init__(self):
self.h = []
self.push = lambda x: heappush(self.h, -x)
self.pop = lambda: -heappop(self.h)
self.peak = lambda: -self.h[0]
self.len = lambda: len(self.h)
class minhheap:
def __init__(self):
self.h = []
self.push = lambda x: heappush(self.h, x)
self.pop = lambda: heappop(self.h)
self.peak = lambda: self.h[0]
self.len = lambda: len(self.h)
def kth_min_max():
from heapq import nsmallest, nlargest
# kTh smallest : Keep a min heap of size k. O(n log k)
h, k = [], 3
for i in [5, 2, 1, 7, 4, 2, 8, 10, 2]:
if len(h) < k:
heappush(h, i)
else:
if i > k: heapreplace(h, k)
print("3rd smallest: ", h[0]) # Ex: 65fdd808fcad43b2b2726062aeaa108d
# Build in support for k-min/max in O(n log k) time:
L = [1,2,3,2,5,6,8]
nsmallest(2, L) # ,key=lambda x:x) -> ]
nlargest(2, L) # ,key=lambda x:x) -> [8, 6]
# Performance wise, you get O(n log k) as expected compared to sort:
# L = rand_list(10000000)
# timeit(lambda: sorted(L)[0:6], number=50)
# 44.241248495000036
# timeit(lambda: heapq.nsmallest(6, L), number=50)
# 14.27249390999998
# Time complexity, indirect uses nlargest ref: https://stackoverflow.com/questions/29240807/python-collections-counter-most-common-complexity/29240949
def heapq_with_classes():
# In general,
import heapq
class Person:
def __init__(self, name, age, height):
self.name = name
self.age = age
self.height = height
def __lt__(self, other):
return self.age < other.age # set to > for max heap.
def __repr__(self):
return "{} {} {}".format(self.name, self.age, self.height)
people = [
Person("Leo", 31, 168),
Person("Valarie", 19, 157),
Person("Jane", 20, 150),
Person("Bob", 40, 170),
Person("M.Jordon", 45, 210)
]
print(heapq.nlargest(2, people, key=lambda x: x.height)[1].name) # bob.
heapq.heapify(people)
while people:
print(heapq.heappop(people))
# Bob
# Valarie 19 157
# Jane 20 150
# Leo 31 168
# Bob 40 170
# M.Jordon 45 210
def runtime_complexities_O(n):
# Ref: Text
# https://www.ics.uci.edu/~pattis/ICS-33/lectures/complexitypython.txt
# Ref:
# https://wiki.python.org/moin/TimeComplexity
# Algorithm Cheat Sheet:
# http://bigocheatsheet.com/
# List:
# index l[i] O(1)
# store l[i]=1 O(1)
# len len(l) O(1)
# l.append(1) O(1) *avrg/amortized.
# sort l.sort() O(n)
# Set:
# av worste
# add O(1)
# in O(1) O(n)?
# pop O(1)
pass
def bit_wise_ops():
# https://wiki.python.org/moin/BitwiseOperators
# A << 1 # move bits left by 1.
# B >> 1
# A & B A | B A ^ B ~A
pass
def module_import():
# Module import
# import module_name
# from module_name import name , .. | *
pass
def asterisk_usage():
# Has many useages.
# * list, position args,
# ** dist, keyword args,
# in funcs, expand args to list/dict
# in args to func, unpack list/dict : myFunc(*[1,2,3]) -> myFunc(1,2,3)
# in assignment, dynamically assign to list/dict
# https://medium.com/understand-the-python/understanding-the-asterisk-of-python-8b9daaa4a558
# Zip/Unzip used for unpackaging/packaging lists.
list(zip([1, 2, 3], ["a", "b", "c"]))
#[(1, 'a'), (2, 'b'), (3, 'c')]
# Ex: https://www.hackerrank.com/challenges/zipped/problem
pass
def stdin_console_input():
# myvar = input() # python 2: input expression. python 3: input string. Use eval(..)
# print (myvar) # 1 + 1 -> 2
# Problem: https://www.hackerrank.com/challenges/input/problem
# myvar2 = raw_input() # Python 2: input string. python 3: gone.
# print (myvar2) # 1 + 1 -> '1 + 1'
# Splitting input into list/dic:
# Problem: https://www.hackerrank.com/challenges/finding-the-percentage/problem
pass
def Classes():
# c88fb2fff01f444ca67d892a202078c3 -> cheatcheet
class myClass:
def __init__(self, val):
self.val = val
def __repr__(self):
return self.val
# Augment classes on the fly:
mc = myClass("MyVal")
hasattr(mc, "myAttr") # False
mc.myAttr = "hello"
hasattr(mc, "myAttr") # True
# ref: https://stackoverflow.com/questions/610883/how-to-know-if-an-object-has-an-attribute-in-python
def class_basic():
# class MyClass:
# #someVar = 5 #Instance var sample.
#
# my = MyClass();
# print (my.x) # 5