[go: up one dir, main page]

0% found this document useful (0 votes)
38 views3 pages

CS1010S Cheatsheet

The document covers various programming concepts including precedence of operators, for loops, recursion, and list operations in Python. It explains the use of lambda functions, map and filter functions, and dictionary methods. Additionally, it touches on class inheritance and provides examples of common programming tasks such as summation and removing duplicates.

Uploaded by

yanri03
Copyright
© © All Rights Reserved
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% found this document useful (0 votes)
38 views3 pages

CS1010S Cheatsheet

The document covers various programming concepts including precedence of operators, for loops, recursion, and list operations in Python. It explains the use of lambda functions, map and filter functions, and dictionary methods. Additionally, it touches on class inheritance and provides examples of common programming tasks such as summation and removing duplicates.

Uploaded by

yanri03
Copyright
© © All Rights Reserved
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/ 3

Precedence: Lecture 4: For Loops lambda x: x(something)

() Parentheses - Sequence: a sequence of va lues (iterables) map(lambda x: x*x, nums)


** Exponent - Var: variable that take each value in the sequence. filter(lambda x: x==0, nums)
+x, -x, ~x Unary plus, Unary minus, Bitwise NOT o Defined in a global scope.
*, /, //, % Multiplication, Division, Floor division, List Operation
o Var is redefined every time the for loop is called again
Modulus - Body: statement(s) that will be evaluated for each
+, - Addition, Subtraction lst.append(elem),
value in the sequence Range: Used to create sequence add elem to end of lst, NO return value (return
==, !=, >, >=, <, <= of integers None)
is, is no - From start (inclusive) to stop (non-inclusive) lst.extend(seq),
in, not in - Incremented by step add all elements in seq to end of lst, No return
not Logical NOT value
and Logical AND Advanced Recursion lst.insert(idx, elem),
or Logical OR Order of Recursive Calls: insert elem to the index idx of lst, No return
- In case of the same precedence, the left-to-right - Pre-order: Complete actions before calling value
associativity is followed. However, the exponentiation recursive functions ; ends with base case. lst.remove(elem),
operator (**) is an exception that follows right-to left def preorder(n): remove first occurrence of elem from lst, if no
associativity. if n==0: such elem, raises Value error, No return value
- Strings should not contain backlashes, e.g. 'python\': return lst.pop()/lst.pop(idx)
Backslash in computer science is commonly used to print(n). #action occur before recursive call remove last item or item at idx from lst, raises
escape the character behind it but will not be printed out. preorder(n-1) IndexError if idx is out of range, Return the
e.g print('\'Great!\', he said.') gives 'Great!', he said. preorder(3)-> 3 2 1 removed item
- Normal division (/) always returns a float; Integer division - Post-order: Complete actions after calling lst.clear()
(//) always returns an Integer. recursive functions ; starts with base case. Remove all items from the list lst, No return val
- When comparing strings, string alphabetically (ASCII for def postorder(n): lst.copy()
non-letters) in front has smaller value. if n==0: Makes a shallow copt of the list lst (lst[:]), returns
return shallow copy
- 0 ** 0 == 1 postorder(n-1) lst.reverse()
- %(modulo) (eg. A % B) always return positive value print(n) Reverse the elements of lst in place, No return
for positive B, like modulo (2%5 = 2 or -3); else returns preorder(3) -> 1 2 3 value
negative value for negative B - A % B = A- ((A//B)*B)
Recursion (a function that calls itself) Tuple sorted(seq, key = lambda x: x[0], reverse =
def setpixel(image, row, col, pixel): Boolean)
- Base step: Terminating condition res = () key can be used to sort specific elements in a
- Recursive step: Function calls itself to do simpler case for r in range(len(image)): nested list, normal sorted just need to supply seq.
- Linear Recursive Functions: recursive functions that call rows = () reverse = Boolean can be used to sort in
themselves at most one time on each call (i.e., each branch for c in range(len(image[0])): descending order.
either calls itself once or none at all). While in Python if r == row and c == col:
- Expression: Predicate(condition) to stay in loop rows = rows +(pixel,) map(lambda x: x[0], seq)
- Body: Statement(s) to be evaluated if predicate is True else: map(lambda x: [x[0],x[1]], seq)
- break: Exit the loop prematurely before its normal rows = rows + (image[r][c])
termination process is made - continue: Skip the rest of the res = res + (rows,)
code inside a loop for the current iteration and move to the return res
next iteration.
- Steps: Initialization: set the result and condition variable Map, Filter, Lambda
to an initial value at the beginning -> Accumulation:
accumulate result one-by-one ->Return map(function, iterable)
-map applies a function to every item in the
def factorial(n): iterable, eg. List
if n == 0: filter(function, iterable)
return 1 -function is a Boolean predicate that returns True
else: or False, filter applies function to all items and
return n*factorial(n-1) keeps items that return True
super(). __init__(same variable as above)
self. Extra = attribute
Dictionary

dict.values() – returns a view of dictionaryvalues Overriding:


dict.keys() – returns a view of the dictionary Def get_mark(self): def get_count(fname, assessment, threshold):
keys If self.graduated:
dict.items() – returns view of key-value tuple Return super().getmark() data = read_csv(fname)
pair Isinstance(obj,class):
Check if obj is subclass of Class. Return Boolean if assessment == 'CA': max_marks = 50
dict.get(key,default) – return value for key, else,
return default value elif assessment == 'Midterm': max_marks = 60
dict.pop(key,default) – removes and returns
value of key, return default if provided Pritning using f- stringsL elif assessment == 'Project': max_marks = 20
dict.popitem() – remove and return last key- Print( f “ text … {return}…”)
else: max_marks = 100
value pair, key error if empty
dict.update(otherdict) – update dictionary with Summation col = data[0].index(assessment)
key-value pair from another dict, return none grouped = {}
for row in data: count = 0
dict.clear() – removes all items from dictionary,
return none key = row[0]
for row in data[1:]:
dict.setdefault() – returns value for key; sets it to value = row[-1]
default if not present If key not in grouped: if 100 * float(row[col]) / max_marks >= threshold: count += 1
grouped[key] = row.copy() return count
translation from list to dictionary: grouped[key][-1] = value
grouped[key][-1] += value result = [x for x in data if x > 50]
def matrictofaculty(cls):
result = list(grouped.values()) result = []
res = {}
for x in data:
for matric in cls:
Removing duplicates based on indice if x > 50:
fac = getfaculty(cls[matric])
seen = [] result.append(x)
if fac not in res:
res[fac] = [] result = []
marks = [60, 70, 90]
res[fac].append(cls[matric])
for row in data: all(m >= 50 for m in marks)
return res
key = row[1] # this is x[1] true if all
Class if key not in seen:
seen.append(key) # Track this value marks = [60, 35, 90]
result.append(row) any(m < 40 for m in marks)
def __init__(self, initalise variation):
true if 1
self.var1 = var1 all(x in biglist for x in smalllist)
self.attr = something
fruits = ['apple', 'banana', 'cherry']
any(x in biglist for x in smalllist) fruit_dict = {}
For inheritance
for index, fruit in enumerate(fruits):
class Child(Parent):
fruit_dict[index] = fruit
pass (takes every attribute and method)
for key, value in original_dict.items():
class Child(Parrent):
def __init__ (self, same variables as above, swapped_dict[value] = key
extra):

You might also like