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 ) ]