Python Flashcards
any( )
The any( ) function returns True if any element of an iterable is True. If not, it returns False.
boolean_list = [‘True’, ‘False’, ‘True’]
# check if any element is true result = any(boolean_list) print(result)
=> Output: True
zip( )
The zip( ) function takes iterables (can be zero or more), aggregates them in a tuple, and returns it. [returns zip object => list( ) for array]
languages = ['Java', 'Python', 'JavaScript'] versions = [14, 3, 6]
result = zip(languages, versions)
print(list(result))
Output: [(‘Java’, 14), (‘Python’, 3), (‘JavaScript’, 6)]
List comprehension
fruits = [“apple”, “banana”, “cherry”, “kiwi”, “mango”]
newlist = [x for x in fruits if “a” in x]
print(newlist) #=> ['apple', 'banana', 'mango']
arr = [1,2,3]
for i in range( len( arr ) ):
print( i )
0
1
2
for i in range( 5 ):
print( i )
0 1 2 3 4
for i in range( 6, 10 ):
print( i )
6
7
8
9
ratio_of_users = { “friends”: 6, “influencers”: 2, “fans”: 1, “strangers”: 1 }
print( type( ratio_of_users.values( )) )
print( ratio_of_users.values( ) )
dict_values( [6, 2, 1, 1] )
=> use like: list( ratio_of_users.values( ) )
Generate random number
import random
random.randrange( 3 )
=> similar to range(int), this outputs a random int from 0, 1, 2 [not 3!!]
# as a result, works great for lists: list[ randrange( len(list) ) ] => random element from list
Propend character to string
BEST:
- strings are immutable objects: Need to be copied every time changed
- > Use a mutable object
append_to_this = " :Append here" pre_in_reverse = list( range( 1, 11 ) ) pre_in_reverse.reverse( ) string_version = "".join( [ str( e ) for e in pre_in_reverse ] ) return string_version + append_to_this
FINE IF ONCE:
s = “48”
s = str(1) + s
=> “148”
Python set
- initialize
- operations
s1 = set( ) s2 = set( 3, 2, "string", ("a", 2, "c") ) s3 = { 3, 2, "string" }
3 in s2 => True // O(1) <=!!!!!!
s. update( (1,) ) => must be a set itself
s. remove( x ) => key error if not present
s. discard( x ) => removes without error if not present
s. pop( ) => removes and returns random element
s. clear( ) => removes all elements from set
s3 = s1.union( s2 ) => not a mutation! Doesn't change s1 s3 = s1.intersection( s2 ) => not a mutation! Doesn't change s1 s3 = s1.difference( s2 ) => // difference: also -> s1 - s2
dict operations
Hash tables:
- elements allocated through hash function
- search O( 1 )
h = dict( ) h = { 'a': 1, 'b': 2 }
h. items( ) => Returns a LIST containing a tuple for each key value pair
h. keys( ) => Returns a LIST containing the dictionary’s keys
h. values( ) => Returns a LIST containing the dictionary’s values
h. clear( ) => Removes all the elements from the dictionary
h. copy( ) => Returns a copy of the dictionary
h. popitem( ) => Removes the last inserted key-value pair
h.pop( ‘a’ ) => deletes key value pair of key ‘a’ AND returns Value
h.pop( ‘a’, returnValue ) => deletes key value pair of key ‘a’ AND returns the second parameter ONLY if not found!
del h[ ‘a’ ] => deletes key value pair of key ‘a’,
h. get( ‘a’ ) => Returns the value of the specified key -> same as h[‘a’], but NO KEY ERROR if doesn’t exist
h. get( ‘a’, returnValue ) => Returns the value of the specified key. If doesn’t exist, returns value 2nd param
h. update( { ‘a’: 1 } ) => Updates the value of key a to 1
Check if key ‘a’ is in dict h
Check if value 1 is in dict h
‘a’ in h
1 in h.values( )
Length of dict h
len( h )
=> by default, dict refers to the keys.
E.g. ‘a’ in h => bool
Reverse python iterable
E.g. string, list
s = “hallo”
s[ : : -1 ]
=> ollah
Time complexity: O( n )
For list:
list. reverse( )
- > Mutable vs immutable object
Round numbers up or down to ints
import math
math. ceil( 5/3 ) => 3
math. floor( 5/3 ) => 2
Find greatest common divisor (GCD)
import math
math.gcd( 9, 30 ) => 3
type( 15 / 3 )
=> float
If you need type int:
int( 15 / 3 )
Create a matrix with m rows and n columns
All zeros
matrix = [ [ 0 for j in range( n )] for i in range ( m ) ]
for j in range(1,5):
print(j)
1
2
3
4
PEP8 naming convention: Classes
Model, MyClass
Start each word with a capital letter. Do not separate words with underscores. This style is called camel case.
PEP8 naming convention: Modules
module.py, my_module.py
Use a short, lowercase word or words. Separate words with underscores to improve readability.
PEP8 naming convention: Package
package, mypackage
Use a short, lowercase word or words. Do not separate words with underscores.
PEP8 naming convention: Functions, methods, variables
my_function, my_variable, class_method
Use a lowercase single letter, word, or words. Separate words with underscores to improve readability.
print all odd numbers from 0 to 101 (including)
for i in range( 1, 102, 2 ):
print( i )
- Third argument is skips
- Choose right start number for odd / even
Prepend to list
my_list = [ 2, 3 ]
my_list.insert( 0, 1 )
my_list => [ 1, 2, 3 ]
Syntax:
list.insert( idx, element )
list the alphabet
import string
list( string.ascii_lowercase )
Double ended queue Python
import collections
normal_list = [ 1, 2, 3, 4 ] deque_list = collections.deque( normal_list )
METHODS append( ): This function is used to insert the value in its argument to the right end of the deque.
appendleft( ): This function is used to insert the value in its argument to the left end of the deque.
pop( ): This function is used to delete an argument from the right end of the deque.
popleft( ): This function is used to delete an argument from the left end of the deque.
__funcxx__
Magic or Dunder methods
invocation happens internally from the class on a certain action. For example, when you add two numbers using the + operator, internally, the __add__() method will be called.
num=10 num + 5 => 15 num.\_\_add\_\_(5) => 15
arr = [ 1, 2 ] b = arr.append( 4 )
print( b )
None
!! list.append(x) doesn’t return anything !!
It only updates the list
print( list( range( 3, 2 ) )
[ ]
=> important when iterating n^2 without repeating elements
len_nums = len(nums)
for a in range(len_nums):
for b in range(a+1, len_nums):
sum = nums[a] + nums[b]
=> works
print( [ 1,2 ] == [ 2,1 ] )
False
Two different lists - they are ordered
print( ( 1,2 ) == ( 2,1 ) )
False
Two different tuples - they are ordered
word = “w”
print( word[ 1 : ] )
my_list = [ 1 ]
print( my_list[ 1 : ] )
=> “”
=> [ ]
(important for recursive algorithms)
Parameter vs Argument
The terms parameter and argument can be used for the same thing:
Information that are passed into a function. From a function’s perspective: A parameter is the variable listed inside the parentheses in the function definition. An argument is the value that are sent to the function when it is called.
def foo( x: str ): # x -> parameter pass
foo( “word” ) # “word” -> argument
foo
‘foo’ is just a general, meaningless placeholder used in coding
def foo( x: int ): print( x )
merge two lists
l1 = ["a", "b" , "c"] l2 = [1, 2, 3]
merged_list = l1 + l2
=> [‘a’, ‘b’, ‘c’, 1, 2, 3]
Remove item from list by index
list.pop(idx)
l = [ 1, 2, 3 ]
l.pop( 1 )
Iterate through an array or string with index
for ele, idx in enumerate( arr ):
print( idx, ele )
for idx in range( len( arr ) ):
print( idx, arr[ idx ] )
Iterate through an array / string from back to front
for i in range ( len( arr ) - 1, -1, -1 ):
print( i, arr[ i ] )
arr_2d = [ [“a”, “b”], [“c”, “d”], [“e”, “f”] ] # assume all sub_arrays hold pairs
Iterate through the pairs
for first_val, second_val in arr_2d:
print( first_val )
print( second_val )i
Convert string s = “What’s up?” to a list
list( s )
=> [‘W’, ‘h’, ‘a’, ‘t’, “’”, ‘s’, ‘ ‘, ‘u’, ‘p’, ‘?’]
note whitespace
Create defaultdict with 0 as default value
import collections
dd = collections.defaultdict( int )
dd[ ‘new_key’ ] += 1
print( dd )
=> defaultdict( , { ‘new_key’: 1 } )
Iterating through list and comparing adjacent elements
With a regular iteration, you would run into an index error at the beginning or end.w
Solution:
If comparing each element to prior, start at idx 1 => for i in range(1, len(arr))
If comparing each element to following element +> for in range( 0, len(arr)-1)
Make list a string - join elements
l = [‘a’, ‘b’, ‘b’]
Desired output: “abc”
[add other versions: non homogeneous lists etc)
https://www.simplilearn.com/tutorials/python-tutorial/list-to-string-in-python
’‘.join( l )
continue statement
‘continue’ skips an iteration in a for or while loop.
for i in range(4): if i == 2: continue print( i )
=> 0, 1, 3
break statement
‘break’ stops a for or while loop.
for i in range(4): if i == 2: break print( i )
=> 0, 1
Round a number to closest integer
round( )
Directly integrated in python.
E.g. round(13/4) == 3