Cheatography

# CS1010S Mid terms Cheat Sheet by anglimin

### Types

 str 'abcd' int 1,2,3,4 float 1.23 bool True/False None None type('­abc') shows the type of the object type conversion int('123') --> 123 bool(x) False for x values that are null or empty x. True for otherwise Naming conven­tions lowercase and underscore (_HAPP­Yday, happyday)

### Order of growth

 def factor­ial(n): if n < 2: return 1 return n * factor­ial(n - 1) O(n) def fib(n): if n < 2: return 1 return fib(n - 1) + fib(n - 2) O(2^n) (each branch produces another 2 branches) def foo(n): while n > 1: print(n) n = n // 2 O(log n) def bar(n): while n > 1: x = n while x > 1: print(n, x) x -= 1 n -= 1 O(n^2) (loop in a loop) def baz(n): while n > 1: x = n while x > 1: print(n, x) x = x // 2 n -= 1 O(n log n) (log n in a loop) String and tuple slicing Slicing is an O(n) operation as you need to create another string­/tuple when you slice. def count_­me(n): if n < 10: return n else: return count_me(n + 1) O(infi­nity) String and tuple concat­enation O(n)
Time comple­xit­y--> looking at the branches of the tree
Space comple­xit­y--> looking at the depth of the tree (depends on the pending operations the function incurred)

And also for analysing OOG questions:
for <lo­op>:
<do work>
Time
= work(1) + work(2­)+...+­work(n)
If work is fixed (let's say work = k) regardless of n, Time = n * k
Otherwise,
Time = sum of work
Remember to state what the n means

### Recursive and Iteration

 ``````Recursion def recusive_fn(n):     if :         return     else:         return Iteration (for or while loop) def iterative_fn(n):     temp =     for i in :             return temp def factorial (n):     product , counter = 1,1     while counter <= n:        product *= counter        counter += 1     return product``````

### Tuples comparison

 ``Tuples are compared position by position: the first item of the first tuple is compared to the first item of the second tuple (same as string); if they are not equal (i.e. the first is greater or smaller than the second) then that's the result of the comparison, else the second item is considered, then the third and so on.``

### Truth Tables ### Truth values revisited

 ``````Truth and False will be represented by 1 and 0 respectively. not 'abc' --> False 1 or 0 --> 0 '' is same as False is same as 0 is same as [] while True: infinite looping while False: will not loop at all``````

### Unboun­dLo­cal­Error ### String and tuple slicing

 ``````s[start:stop(noninclusive):step] eg) s = "12345", d ='6789' concatenate--> s + d--> '123456789' s = "1", s[1:]= "2345", s[:2]= "12", s[1:5:2] = "13" s[-1] = "5", s[-1:-3] = "", s[-3:-1]= '34', s[-5:-1:2]= '13', s[-5:-1:-2]= ''', s[-1:-5:-2] = '53'``````

### Variable (Global and Local) Variable is local if assigned to in function
Namespaces match function and variable names to their defini­tions and assign­ments

### Random module

 random.ra­ndi­nt(a, b) Return a random integer N such that a <= N <= b. random.ra­ndr­ang­e(s­tart, stop[, step]) Return a randomly selected element from range(­start, stop, step). This is equivalent to choice­(ra­nge­(start, stop, step)), but doesn’t actually build a range object random.ra­ndom() Return the next random floating point number in the range [0.0, 1.0). random.ra­ndom() can be scaled int(ra­ndo­m.r­andom() * 9999) → 3658

### break

 ``````for val in "string":     if val == "i":         break     print(val) print("The end") Output: s t r The end``````
The break statement terminates the loop containing it. Control of the program flows to the statement immedi­ately after the body of the loop.

If break statement is inside a nested loop (loop inside another loop), break will terminate the innermost loop.

### Hiding 'somet­hing'

 ``````Input an empty (lambda : "Prof is really cool") In that way what is printed or sliced/accessed will be the function itself. To recover the secret message, can input () at the back.``````

### Functions

 ``````def (formal parameters):    body    return (something if not it is going to return to zero) Anonymous function→ lambda lambda x: x+ 1 A function need not use every parameter passed into it. (def foo(a, b): return a + a) A function without any parameters or return value is still valid. (def foo():return ) Functions do not necessarily need a return value.(def foo(a, b, c):a + b + c)``````

### Condit­ionals

 ``````if :     do something elif :     do something else :    do something while :    do something``````

### Equality/ in function

 is This means the same object. (3 is 3)--> True == This mean the same content. (3.00 == 3) --> True in check the elements inside the other group. Eg) x = (1,2,3). 1 in x--> True

### OOG Time and Speed ### Different Types of Error

 NameError Raised when a variable is not found in local or global scope. IndexError Raised when index of a sequence is out of range. Runtim­eError Raised when an error does not fall under any other category. Syntax­Error Raised by parser when syntax error is encoun­tered ZeroDi­vis­ion­Error Raised when second operand of division or modulo operation is zero. Unboun­dLo­cal­Error Raised when a reference is made to a local variable in a function or method, but no value has been bound to that variable Recurs­ion­Error Infinite looping

### Tuple and string functions

 len() Return the length (the number of items) in the tuple. max() Return the largest item in the tuple. min() Return the smallest item in the tuple sum() Retrun the sum of all elements in the tuple. tuple() Convert an iterable (list, string, set, dictio­nary) to a tuple. count() count the occurr­ences of an element in a tuple index() Searches the string for a specified value and returns the position of where it was found

### continue

 ``````for val in "string":     if val == "i":         continue     print(val) print("The end") Output: s t r n g The end``````
The continue statement is used to skip the rest of the code inside a loop for the current iteration only. Loop does not terminate but continues on with the next iteration.