0% found this document useful (0 votes)
154 views

Python Cheat Codes

Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
154 views

Python Cheat Codes

Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 9
‘A whole, made up of parts— difficult to analyze, understand, cor explain’. Majority of effects come from the minority of causes seeteeeeee i You Ain't Gaing to Need It ‘Simple's Better Than ‘The Principle of Least Surprise Complex Don't Repeat Yourself Stand on the Shoulders o Use the Right Names Single-Responsibility Prin Use Comments ‘Avoid Unnecessary Comments Use Software Leverage Be Consistent Test Thinkin Big Pictures (Only Talk to Your Friends Refactor Clean > Clever Code Don't Overengineer 7 Don't Overuse Indentation ‘Make Your Code Robust, ‘Small is Beautiful Use Metres Boy Scout Rule: Leave Car Cleaner Than You Found ‘Complexity appears in Project Lifecycle Code Development Algorithmic Theory Processes Socal Networks Learning & Your Daly Lite Pareto Tips 1, Figure out your success metrics. 2. Figure out your big goals nif. 3. Look for ways to achieve the same. things with fewer resources. 4. Reflect on your own successes 5. Reflect on your own failures 6. Read more books in your industry 7. Spend much af your time Improving and tweaking existing products 8 Smile 9. _Don'tdo things that reduce value Maximize Success Metric: ‘Make Each Program Do One fGiants}| Thing Well Build a Prototype First ciple Portability Over Efficiency Store Data in Flat Text Files Avoid Captive User Interfaces Worse is Better Repair What You Can — But Fall Early and Nosily mp Write Programsto Write te Programs How to Simplify Design? Use whitespace Remove design elements Remove features Reduce variation of font, font types, colors 5. Be consistent across Us ec “eam aie Rocce ee. eres Oa) 2 aware» | “Sie 2 ‘Aminimumvable > Gt sic ma, ih | ah software sense is code a? -_ | ‘thatis stripped from all features to focus on ‘the core functionality. _ vowtomrs one + split test to validate ‘each new feature Focus on product- market ft Seek high-value and \ low-cost features _) Renee Performance Tuning 201 1. Measut, then improve "Programmers wste enormous 2._~Focusan the slow 20% ameunts of time thinking about.) 3. Algorithmic optimization the speed of noncritical pats of te wins programs. We should forget about 4. _Allhailto the cache ‘small efficiencies, say about 97% of 5. _Solve an easier problem the time: version Donald Knuth Know when to stop. Ea the source code of ultimate human performance” Kotler ) Flow Tips for Coders ‘Always work on an explicit practical code project Work on fun projects that fulfill your purpose Perform from your strengths Big chunks of coding time Reduce distractions: smartahone + socal Sleep aot, eat heathly, read quality books, and exercise > garbage'n, garbage out! using focused effort towards th lateainment ofa greater plan, "You can take raw resources and move them from a state of high lentropy into a state of low entropy— omg 2 Efficient Software Creation Step Approach of Pianyourcode — P®Y Apply focused effort Oe to make it real. Seek feedoack Name a.shape a.ndim np. mataul (a,b), ag np-arange([start, }stop, Istep, 1) np.Linspace(start, stop, "p. = np. np. np. np. np. np. np. np. np. average(a) «val> var(a) std(a) aifF(a) ‘cursun(a) sort(a) argsort(a) mnax(a) -argnax(a) nonzero(a) Python Cheat Sheet: NumPy “A puzzle a day to learn, code, and play” + Visit finxter.com Description The shape attribute of NumPy array a keeps a tuple of Integers. Each integer describes the number of elements of the axis, The nim attribute is equal to the length of the shape tuple, The asterisk (star) operator performs the Hadamard product, Le,, muttplles two matrices with equal shape element-wise The standard matrix mutiplication operator. Equivalent to the @ operator. Creates a new 1D numpy array with evenly spaced values Creates a new 1D numpy array with evenly spread elements within the given interval ‘Averages over al the values in the numpy array Replace the as selected by the slicing operator with the value 2), True == (2 > 1) and, or, not Logical operators: x, y= True, False (x and y) * both x and y must be True (x or y) == True # True (x or y) * either x ory must be True (x and y) == False # True (not x) +x must be false (not y) == True # True break Ends loop prematurely while(True): break # no infinite loop print("hello world") continue Finishes current loop iteration while(True): continue print("43") # dead code class Defines a new class + a real-world concept class seer: (object oriented programming) def _init_(self): self.content = 1.0 def Defines a new function or class method. For latter, def drink(self) st parameter ("sel") points to the class object. When calling class method, first parameter is implicit self. content 2.0 becks = Beer() # constructor - create class becks.drink() # beer empty: b.content == 0 if, elif, else Conditional program execution: program starts with if" branch, ties the “elif branches, and finishes with x = int (input ("your value: if x > 3: print("Big") » ‘else" branch (until one branch evaluates to True). | elif x == 3: print("Mediun”) else: print("Smali") for, while 4 For loop declaration # While loop - sane semantics for 4 in [8,1,2] 5 print(i) while J <3: print(3) jegjea in Checks whether element is in sequence 42 in [2, 38, 42] # True is Checks whether both elements point tothe same | y 3 object xis y # True [3] {5 [3] # False None Empty value constant def £0 xe? 0) 1s None # True anbda Function with no name (anonymous function) (anda x: x + 3)(3) # retuens 6 return Terminates execution of the function and passes the | def increnentor(x): flow of execution to the caller. An optional value after the return keyword specifies the function result return x #2 incrementor(4) # returns 5 finxter Python Cheat Sheet: 14 Interview Questions “A puzzle a day to learn, code, and play” + Visit finxter.com Question code auestion | code Chockiflist 1 = [3, 3, 4, 5, 24 112, 5) Got missing def get missing nunber(ist) contains print(ia1 dn 1) # Tove number in return set(range(ist[len(1st)-1])[1:]) = set(.) Integer x [1.100] 2 = List(range(a,100)) 1 .renove(s@) print (get missing nunber()) # 50 Find duplicate Compute def ntersect(Istt, 1st2): ‘number in duplicates, seen = set(), set() the res, Ist2_copy = (J, Ist2[:] Integer list for elerent in elements Intersection for el in Ist: 4 elesent in seen of two lists Sf el in 1582_copy: duplicates. add(elenent) es. append(el) seen.add(elenent) 1st2_copy..renove(el) return List (duplicates) return res Checkiftwo def 4s_snagram(st, 52) Find max 1» (4, 3, 6, 3, 4 888, 4, -11, 22, 3] strings are return set(si) == set(s2) fandimin in print(nax(2)) # 888 anagrams print(is_anagran(“elvis", “Lives")) # True unsorted list print(nin(2)) # 7 Remove al range(18)) + List(range(ie)) Reverse def reverse( string) duplicates trom ee(1st)) string using F en(string)<-1: return string list print (ast) recursion return reversetatringtae estranat@] #181 2345678 prist(reverse("*hello")) # oleh Find pairs of def find_pairs(1, x) Compute a, 5-8 2 Intogersiniist. pairs = [] thefirstn n= 10 so that their for (3, ©1_1) in enunerste(1) Fibonacci for 4 in range(n) ‘sum is equal to for (J, e12) Sn enunerate(a[sv2:]): numbers print(o) Integer x ifela + el2 = x a, b= by ab pairs.append((el_1, €1_2)) ena 58 return pairs Checkita def s_palindrone(hrace) Sortlistwith def qsort(L) string isa return phrase == phrase[:: Quicksort af U == []: return [] palindrome | print(is_palindrone("anna")) # algorithm return qsort({x for x in L[i:] 4# xe L[@}]) + Lesa] + qsort((x for x an L[1:] iF x0=L[@)]) Ast = [44, 33, 22, 5, 77, 35, 999] prise (qsore(ise)) #15, 22, 33 5, 77, 999] Uselistas yas 9 List Find all def get_pereutations(x): stack array, 1 = [3, 4] Permutation i Len(w)<=a andqueve ss (5, 6] 1-13, 4, 5, 6 Sof string return set(x) smaller = get_perautations(u[1:1) fos. as a stack perms = set() Leappend(2e) #1 = [4, 5, 6, 2 for x in smaller: 1.00) 4, 5, 6] for pos in range(@, ien(x)*4) pers = x[:p0s] + [8] + xfpos:] fs. and as 2 queue peres.adé(pera) Leinsert(@, 5) #1 = (5, 4 5, 6 return peras Lepop() #1 = (5, 4, 5] prist(get_permutations("nan")) finxter Python Cheat Sheet: Functions and Tricks “A puzzle a day to learn, code, and play” + Visit finxter.com map(func, iter) mmap(func, 41, ik) string. join(iter) Filter(fune, iterable) string. strip() sorted(iter) sorted(iter, keyskey) hetp(func) zip(i1, 12, «-.) Unzip enunerate(iter) python -m http.server oe Read comic Zen of Python Swapping numbers Unpacking arguments Extended Unpacking Merge two dictionaries, Description Executes the function on all elements of the terable: Executes the function on all elements of the k terables Concatenates iterable elements separates by string Filters out elements in terable for which function returns False (0: 0) Removes leading and traling whitespaces of sting Sorts iterable in ascending order Sorts according to the key funetion in ascending order Returns documentation of Fune Groups the Lth elements of Rerators 41, 42, ... together Equal to: unpack the zipped lst, 2) zip the result Assigns a counter value to each element of the iterable Example List(map(lanbda x: x[@], ['red", green’, "blue })) List(map(lanbda x, y y's, [, 2, 2], ('apple’, ‘orange’, ‘banana"})) marries *.join(list({‘Alice’, "B0b'})) List(filter(lanbéa x: True if 3917 else False, [1, 15, 17, 18])) print("\n \t 42. \t “.steip()) sorted([8, 3, 2, 42, 5]) sorted([, 3, 2, 42, 5], keyslanbda x: @ Lf xeed2 else x) hetp(str.upper()) List(zip({"Alice’, ‘Anna'], ["B0b", "Jon", 'Frank')) List(zip(*[(‘Alice’, "B0b"), Anna", "30n')])) List(enumerate({ ‘Alice’, ‘Bob’, 3on"})) stro) + + Result Prt, et) (bd ['@ apples’, 2 oranges’, ‘2 bananas") Alice marries Bob: [a8] 42 12, 3, 5, 8, 42] [42, 2, 3, 5, 8] ‘to uppercase." [(Alice’, "B0b"), anna", *Jon")] [CAlice’, ‘anna"), ("Bob", Jon") [(2, ‘Alice'), (1, Bob"), (2, ‘Jon')] ‘Went to share fles between PC and phone? Run this command in PC’s shell,

Is any port number 0-65535, Type < IP address of PC>:

in the phone's browser, You can now browse the files in the PC directory, import antigravity import this ‘Swapping variables is a breeze in Python, No offense, Java! Use a sequence as function arguments Via asterisk operator *. Use a dictionary (key, value] via double asterisk operator “* Use unpacking for multite assignment feature in Python Use unpacking to merge two dletionaries Into a single one Open the cor Beautiful is better than ugly. ab abba ne", ‘Alice def F(x, ys 2) CTL, 3, 4]) FOCZ! 4 return x+y * 2 yah a, "= (2, 2,3, 4 5] xe(‘Alice’ : 18} "Bob : 27, ‘Ann’ : 22) (hey) finxter ries xked in your web browser Explicit is a= ‘Alice b= "Jane" 3 3 asi b= 12,3, 4, 5] z= (Alice: 18, Bob": 27, "Ann*: 22} Classes Instance sett Creation Python Cheat Sheet: Classes “A puzzle a day to learn, code, and play” + Visit finxter.com Description A class encapsulates data and functionality: data as attributes, and functionality as methods. tis a blueprint for creating concrete instances in memory. Instances Class aS coe OE Methods commands barktreg) You are an instance of the class human. An instance is @ concrete implementation of a class: all atributes of an instance have a fixed value. Your hair is blond, brown, or black--but never unspecified, Each instance has its own attributes independent of other instances. Yet, class variables are different. These are data values associated with the class, not the instances. Hence, all instance share the same class variable species in the example. The frst argument when defining any method is always the self argument, This argument specifies the Instance on which you call the method, Self gives the Python interpreter the information about the concrete instance. To define @ method, you use self to modify the instance attributes, But to call an instance method, you do not need to specify self You can create classes “on the fly" and use them as logical units to store complex data types. class Enployce() pass ‘enployee = Enployee() cenployee. salary = 122000 enployee.firstnane = "alice" ‘enployee. lastname = “wonderland” print(employee.firstnane + + enployee-lastnane + + str(enployee.salary) + "$ # alice wonderland 122000 Example Blueprint of a dog # class variable shared by all instances species = (“canis lupus") def _init_(self, name, color): self.nane = nane self.state = “sleeping” self.color = color def conmand(self, x): Af x == self.nane: self.bark(2) elif x == "sit™ self.state else: self.state def bark(self, freq): for 4 in range(freq): print("[" + self.nane + "I: Woof") bello alice 10g("bello", “black") jog(“alice", “white") print(bello.color) # black print(alice.color) # white bello.bark(1) # [bello]: Woof! alice.conmand("sit") print(*(alice]: " + alice.state) # [alice]: sit bello. conmand("n0") print("[bello]: " + bello.state) # [bello]: wag tail alice.conmand(“alice") # [alice]: Woof! 4 [alee]: Woof! bello.species += ["wlf"] print (1en(bello. species) len(alice.species)) # True (!) finxter Python Cheat Sheet: Complex Data Types “A puzzle a day to learn, code, and play” + Visit finxtercom Description Example List A container data type thet stores @ 1= [4 2,2] sequence of elements. Unlike strings, lists | print (en(1)) # 3 are mutable: modification possible. Adding Add elements ‘0 alist with () append, (i) [1,25 2]-append(4) # [1, 2, 2, 4] elements | insert, o i ist concatenation. U1, 2, 4]ansert(2,2) # (1, 2, 2, 4] The append operation is very fast. (22) +4) #01, 2 2, 4] Removal | Removing an element can be slower. [1, 2, 2 4]-remove(1) # [2, 2, 4] Reversing | This reverses the order oflist elements. | [1 2, 3]-reverse() # (3, 2, 1] Sorting Sorts a list. The computational complexity [2s 4 2]-sort() # [2, 2, 4] of sorting is supertinear in the no. lst elements Indexing | Finds the first occurrence of an element in [2 2, 4].index(2) # index of elenent 2 is "@" the list & returns its index. Can be slow as [2y 2, 4]-index(2,1) # index of el. 2 after pos 1 is "2" the whole lst is traversed. Stack Python lists can be used intuitively as stack = [3] stacks via the two list operations append) | stack-append(42) # (3, 42] and pop), stack.pop() # 42 (stack: [3)) stack.pop() # 3 (stack: []) Set Asetis an unordered collection of unique basket = {‘apple', ‘eggs’, ‘banana’, ‘orange’} elements (‘at-most-once’). same = set({"apple’, ‘eggs’, ‘banana’, ‘orange’ }) Dictionary |The dictionary is a useful data structure for calories = {"apple’ : 52, ‘banana’ : 89, ‘choco’ : 546} storing (key, value) pairs. Roading and | Read and write elements by specifying the | print(caloriesl‘apple"] < calorses['choco"]) # True writing key within the brackets. Use the keys() and | calorges{ ‘cappu'] = 74 elements | valuesi) functions to access all Keys and print (calories[ ‘banana"] < calories{‘cappu']) # False values of the dictionary. print(‘apple’ in calories.keys()) # True print(52 in calories.values()) # True Dictionary | You can access the (key. value) pairs of @ | for k, v in calories.itens(): Looping _| dictionary with the Atems() method. print(k) if v > 58@ else None # “choco* Membership | Check with the ‘in’ keyword whether the basket = {"apple', ‘eggs’, ‘banana’, ‘orange’} operator | set list, or dictionary contains an element. | print(‘eggs’ in basket) # True Set containment is faster than list print(‘nushroon' in basket) # False containment. List ang Set | List comprehension is the concise Python | # List comprehension Comprehens | way to create lists. Use brackets plusan 1 = [("HL' + x) for x in ['Alice’, "Bob", "Pete']] ion expression, followed by a for clause, Close | print(1) # ["Hi Alice’, ‘Hi Bob", ‘Hi Pete’) with zero or more for or if clauses. Set comprehension is similar to list comprehension. 12 = [x * y for x in range(3) for y in range(3) if xy] print(12) # (8, 0, 2) # Set comprehension squares = { x**2 for x in [0,24] if x <4) # (0, 4} finxter Boolean Integer, Float String Python Cheat Sheet: Basic Data Types “A puzzle a day to learn, code, and play” + Visit finxter.com Description The Boolean data type isa truth value, either True or False. ‘The Boolean operators ordered by priority not x #”ifxis False, then x, else y’ x and y * "if is False, then x, else y x or y *"ifxis False, then y, else x” These comparison operators evaluate to True: <2 and @ ce 1 and 3 > 2 and 2 >=2 and Les and 1 l= 0 # True An integer is a positive or negative number without floating point (e.g. 3). A float is a positive or negative number with floating point precision (e.g. 3.14159265359), ‘The '//’ operator performs integer division. ‘The result is an integer value that is rounded toward the smaller integer number (9.3/2 == 2) Python Strings are sequences of characters. The four main ways to create strings are the following 1. Single quotes "Yes" 2. Double quotes "Yes" 3. Triple quotes (multiline) yes We can’ 4. String method ste(5) == '5' # True 5. Concatenation "Ma" + "hatea” # “wahatea’ ‘These are whitespace characters in strings. © Newline \n © Space \s © Tab Ae Example # 1, Boolean Operations x, y = True, False print(x and not y) # True print(not x and y or x) # True th 2. If condition evaluates to False Af None or @ or @.0 or ** or [] or {} or set(): # None, @, @.8, empty strings, or enpty # container types are evaluated to False print("Dead code") # Not reached ‘iw 3. Arithmetic Operations x y=32 print(x + y) #=5 print(x - y) #=2 print(x * y) # = 6 print(x / y) # = 1.5 print(x // y) # <2 print(x % y) # = 1s print(-x) # = -3 print(abs(-x)) # = 3 print(int(3.9)) # = 3 print(float(3)) # = 3.8 print(x ** y) # = 9 tw 4, Indexing and Slicing = "The youngest pope was 11 years old” print(s(é]) oT print(s[1:3]) # ‘he* print(s[-3:-1]) # ‘ol" print(s(-3:]) # “old” x= s.split() creates string array of words print(x[-3] +" "+ x[-1] +" "+ x[2] + “s") # ‘11 old popes’ #5. Most Important String Methods y=" This is lazy\t\n" print(y.strip()) # Renove Whitespace: ‘This is lazy print(*DrOre*.lower()) # Lowercase: ‘drdre’ print(“attention”.upper()) # Uppercase: ‘ATTENTION’ print("smartphone”.startswith("smart")) # True print("snartphone”.endswith(“phone")) # True print("another".find("other")) # Match index: 2 print("cheat".replace("ch", “n")) # meat” print(’,”.join(("F", "8", “I"])) # °F,8,1" print(len(*Rumpelstiltskin")) # String length: 15 print("ear" in “earth") # Contains: True finxter finxter The Ultimate Python Cheat Sheet e Keywords Basic Data Structures espn Te a or th oe on 3 tmereone a ene ute: None 00cm stings oremstycontaer icak | cio prenatey ies von ro fone weap [Aneeperapcivesr [iF ii aites creroop Reson fccmlaomsuerar pesteie ty) FS femaxSesaisuze.” princi ® yl + ce Det rene neg ein ounds : lesmpessrva—ih [pesneceioatiany + ie cnaon = tse? Serme | Pbonsngs ae HF Tatening ona Silona or 2 suing croton method: See (2) Ghlhe | for i dn to,ae2y Sree Someatcimanawcaten [y= x= 5 131 ie 13) por steis) = t5* |y.steipin ‘atusbue cee aston earl Newnan sgoiniteer, ty 7181) 4 "SI" a renent (ti feces lenhello wéelg") F Lengths 3S ie scaet in eccuit # fe VD Complex Data Structures ) se _|pscnon ante swe _[owceten aoe oy atone Yeading [Rescate cores by cine) © ear sab Taine _[icetrarswsnin [rs Tawar Sire [Seattconeeren enon [sew ris te # & Samet 1 Ba print isa ia catvvorueenn feehehestema() atts fanwenentBreumsngen |) 'sotx econ As 0 Werten [ina witthe Smkepaor Smwomtanrowraei |2,2 1), sndent2et ster [eis onas fires Se staser nant marberih, Sack [Usrytonimaverais |orack = 15) epuator sppnel areal acksappena a2) © (2, 4 Tier [urecomarnencon ihe Son iss tee trees ssn #1 pore eres, slowed by afer Se [anneaeea olen of fuse Cowwineewor | [22 7 (x * y for x is zange(3) Sor this slomers ot mor eer eritcinses Fange(al it soy) #00 2 enc) tat memberp Ot] sane ~ sot tt annie’ Se campeeson was on toa banana Snir ols comprevesin ae

You might also like