The document covers fundamental concepts in programming, including variable types, scope, and functions, emphasizing the importance of computational thinking techniques such as decomposition, pattern recognition, and abstraction. It also discusses recursion, data types, and error handling in Python, providing examples of functions and their structures. Additionally, it outlines guidelines for creating data abstraction functions and includes code snippets for various algorithms.
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0 ratings0% found this document useful (0 votes)
35 views2 pages
CS1010S Cheatsheet
The document covers fundamental concepts in programming, including variable types, scope, and functions, emphasizing the importance of computational thinking techniques such as decomposition, pattern recognition, and abstraction. It also discusses recursion, data types, and error handling in Python, providing examples of functions and their structures. Additionally, it outlines guidelines for creating data abstraction functions and includes code snippets for various algorithms.
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2
Lecture 1: Bound variables: variables bound in a local scope (eg.
formal parameters passed int() #change into integer
Computational Thinking: as arguments in functions) str() #change into string - Decomposition: Breaking the problem into smaller, more manageable parts. - Free variables: used throughout the program (global scope) float() #change into float Pattern Recognition: Recognising which parts are the same and the attributes Global variable: defined in the main body of a file (or the console) Local variable: defined inside a function || is local to the function - accessible bool() #change into boolean that define them. - Abstraction: Filtering out info not needed and generalizing info that is needed. from the point at which it is defined until the end of the function ord() #for character; see ASCII - Algorithms: Creating solutions using a series of ordered steps. Steps to #definition of function Problem Solving: Polya’s Problem Solving Process - If Function A is defined under Function B, then any variables defined under def <name> (<parameters>): Understand the problem -> Make a plan -> Do the plan -> Review Function A are NOT SAID to be defined under Function B <body> - Return can be blank at the back || No return statement. (Return None implicitly) #invocation or call - Calculations can be done without assigning a parameter. <name> (<parameters>) - In cases where global and local variables clash, the variable will return the declaration closest to the variable call. id(variable) #returns ID of variable - Body of function would not run (raise error) until called otherwise. #while loop while <expression>: Lecture 3: Recursion (a function that calls itself) <while_body> - Base step: Terminating condition break Data Types: Integer, Float, String, Boolean - Recursive step: Function calls itself to do simpler case #for loop - True == 1, False == 0 - Linear Recursive Functions: recursive functions that call themselves at most for <var> in <sequence>: Variable Convention: one time on each call (i.e., each branch either calls itself once or none at all). <for_body> - Every variable has name, value (defined) and address (assigned) While in Python #<sequence> can be created by range - Every variable can hold only one value - Expression: Predicate(condition) to stay in loop range(start, stop (not included), step) - Starts with ‘a’-‘z’ or ‘A’-‘Z’ or ‘_’ - Body: Statement(s) to be evaluated if predicate is True x is y iff id(x) == id(y) - Contain only alphanumeric characters or ‘_’ - break: Exit the loop prematurely before its normal termination process is made - Case sensitive - continue: Skip the rest of the code inside a loop for the current iteration and Codes: - Avoid reserved keywords e.g. int,str,type move to the next iteration. - Steps: Initialization: set the result and condition variable to an initial value at Counting Coins - Python convention: lower case words separated by ‘_’ e.g., count_change -> EXAMPLE: ‘_’ is a valid variable. the beginning -> Accumulation: accumulate result one-by-one ->Return def cc(amount, kinds_of_coins,order): Precedence: if amount == 0: () Parentheses Lecture 4: For Loops print(order) ** Exponent - Sequence: a sequence of values (iterables) return 1 +x, -x, ~x Unary plus, Unary minus, Bitwise NOT - Var: variable that take each value in the sequence. elif (amount < 0) or (kinds_of_coins == 0): *, /, //, % Multiplication, Division, Floor division, Modulus +, - o Defined in a global scope. return 0 Addition, Subtraction o Var is redefined every time the for loop is called again else: <<, >> Bitwise shift operators - Body: statement(s) that will be evaluated for each value in the sequence order.append(first_denomination(kinds_of_coins)) & Bitwise AND Range: Used to create sequence of integers return cc(amount-first_denomination(kinds_of_coins),kinds_of_coins,order) ^ Bitwise XOR - From start (inclusive) to stop (non-inclusive) +cc(amount, kinds_of_coins-1,order) | Bitwise OR - Incremented by step ==, !=, >, >=, <, <= def first_denomination(kinds_of_coins): is, is no Lecture 5: Advanced Recursion coins = (1,5,10,20,50) in, not in Order of Recursive Calls: return coins[kinds_of_coins-1] not Logical NOT - Pre-order: Complete actions before calling recursive functions ; ends with base case. def count_change(amount): and Logical AND - Post-order: Complete actions after calling recursive functions return cc(amount,5,[]) or Logical OR ; starts with base case. - In case of the same precedence, the left-to-right associativity is followed. - Any recursive problems can be solved iteratively and vice versa However, the exponentiation operator (**) is an exception that follows right-to Tower of Hanoi Scopes: left associativity. A function in a function is only defined within that function (eg. Function A in def move_tower(size, src, dest, - Strings should not contain backlashes, e.g. 'python\': Backslash in computer Function B; cannot call Function A out of Function B) aux): science is commonly used to escape the character behind it but will not be if size == 0: printed out. e.g print('\'Great!\', he said.') gives 'Great!', he said. Lecture 6: Data Abstraction return True - Normal division (/) always returns a float; Integer division (//) always returns else: an Integer. Identity: same reference in memory / same object - When comparing strings, string alphabetically (ASCII for non-letters) in front - Uses ‘is’ in Python move_tower(size-1, src, aux, dest) has smaller value. - Same id() when run print_move(src, dest) - 0 ** 0 == 1 - May return False when compare numbers (3 is 3.00 is False) move_tower(size-1, aux, dest, src) - %(modulo) (eg. A % B) always return positive value for positive B, like Equivalence: two objects are equivalence (of the same value) even if they are not def print_move(src, dest): modulo (2%5 = 2 or -3); else returns negative value for negative B - A % the same object print("move top disk from ", src," to ", dest) B = A- ((A//B)*B) - Uses ‘==’ in Python move_tower(3,1,2,3) Guidelines for Creating Data Abstraction Functions: Lecture 2: Functions Constructors: To create compound data from primitive data def count(n,num_max): Name: symbols associated with function Selectors (accessors): To access individual components of compound data if n == 0: Parameters (inputs): names used in the body to refer to the arguments of the Predicates: To ask (true/false) questions about compound data Printers: return 1 functions. To display compound data in human-readable form elif n <0 or num_max == 0: Body: statement to be evaluated, normally indented (by 4 spaces per default), can return values as outputs return 0 Functions: return count(n-num_max,num_max)+count(n,num_max-1) Scope: Region where variables are visible type() #determine type of data def num_sum(n): return count(n,n-) - 45 Q 81 u 117 def num_of_possible_path(board,n): if n==0 or not board: . 46 R 82 v 118 return 0 elif len(board) == 1: / 47 S 83 w 119 return 1 num_sum = 0 0 48 T 84 x 120 for i in range(1,n+1,1): num_sum += num_of_possible_path(substring(board,i,len(board),1),n) return num_sum 1 49 U 85 y 121
def substring (s , start , end , step ): 2 50 V 86 z 122
res = "" while start < len( s ) and start < end : 3 51 W 87 { 123 res += s [start] start += step 4 52 X 88 | 124 return res
def factorial ( n ): 5 53 Y 89 } 125
if n == 0 : Types of Errors: return 1 1.SyntaxError: unable to parse code due to violation of language rules Eg. print(a 6 54 Z 90 ~ 126 else : 2.RuntimeError: return n * factorial (n - 1 ) a. NameError: cannot find variable 7 55 [ 91 b.TypeError: operation applied to an inappropriate type, eg. 2 + def factorial_iter ( n ): “a” c.IndexError: access index of sequence out of range d.AttributeError: access attributes/methods that are undefined 8 56 \ 92 result = 1 for i in range (2 , n +1 , 1 ): e. ZeroDivisionError: divide by zero result *= i f. RecursionError: maximum recursion depth exceeded 9 57 ] 93 return result ASCII : 58 ^ 94 def fibonacci ( n ): if n < 2 : (space) 32 D 68 h 104 return n ; 59 (underscore) 95 else : ! 33 E 69 i 105 return fibonacci (n - 1 ) + fibonacci (n - 2 ) < 60 ` 96 " 34 F 70 j 106 def is_prime ( n ): = 61 a 97 if n < 2 : # 35 G 71 k 107 return False elif n <= 3 : > 62 b 98 $ 36 H 72 l 108 return True else : ? 63 c 99 for d in range (2 , int ( n ** 0 . 5 )+ 1 ): % 37 I 73 m 109 if n % d == 0 : @ 64 d 100 return False & 38 J 74 n 110 return True ' 39 K 75 o 111 A 65 e 101