ML / Python Flashcards
Create array from array without reference [python]
a = b[:]
how to declare a list and map? [python]
mp = {} lst = []
How to check if the element is int or array? [python]
for v in data_list: if isinstance(v, int):
Implement decorator which returns function signature and its return value
def debug(func): """ :param func: function """ def wrapper(*args, **kwargs): output = func(*args, **kwargs) return f'{func.\_\_name\_\_}{args} was called and returned {output}' return wrapper
@debug def add(a, b):
How to remove the element from the list with the index? [python]
del lst[i]
how to inherit class in Python?
class Shuttle(Rocket):
how to call super from child class?
super().__init__(name, mission)
What Is Python?
Interpreted high-level object-oriented dynamically-typed scripting language.
python standard data types
numbers, strings, sets, lists, tuples, and dictionaries
Can we update string in Python?
Strings are immutable. Once they are created, they cannot be changed e.g.
a = ‘me’
Updating it will fail:
a[1]=’y’
What if we create variable in for-loop or if ??? [python]
if - we can use it after if
for-loop - we can’t use it
if is_python_awesome:
test_scope = “Python is awesome”
print(test_scope) it is ok
how to use global variable in Python?
TestMode = True def some_function(): global TestMode TestMode = False some_function() print(TestMode)
how to get type of variable in Python?
type(‘farhad’)
–> Returns
what is ‘divmod’ in python?
print(divmod(10,3)) #it will print 3 and 1 as 3*3 = 9 +1 = 10
repeat string in python
‘A’*3 will repeat A three times: AAA
how to reverse string in python?
x = 'abc' x = x[::-1]
how to find index of second ‘a’ in a string? [python]
name = 'farhad' index = name.find('a', 2) # finds index of second a
Regex uses in python for working with strings
split(): splits a string into a list via regex
sub(): replaces matched string via regex
subn(): replaces matched string via regex and returns number of replacements
how to cast variable to type in python?
str(x): To string
int(x): To integer
float(x): To floats
how to remove element from the set in Python?
set. remove(item) — removes item from the set and raises error if it is not present
set. discard(item) — removes item from the set if it is present
how to get any element from the set in python?
set.pop() — returns any item from the set, raises KeyError if the set is empty
operations with sets in python?
a = {1,2,3} b = {3,4,5} c = a.intersection(b) c = a.difference(b) c = a.union(b)
what is pickling in python?
Converting an object into a string and dumping the string into a binary file is known as pickling. The reverse is known as unpickling.
If your function can take in any number of arguments - what to do in python?
then add a * in front of the parameter name: def myfunc(*arguments): return a
what is **arguments in python?
def test(*args, **kargs): print(args) print(kargs) print(args[0]) print(kargs.get('a'))
alpha = ‘alpha’
beta = ‘beta’
test(alpha, beta, a=1, b=2)
(3, 1) (‘alpha’, ‘beta’) {‘a’: 1, ‘b’: 2} alpha 1
It allows you to pass a varying number of keyword arguments to a function.
You can also pass in dictionary values as keyword arguments.
how to use lambda in Python?
variable = lambda arguments: expression
difference == vs is in python?
If we use == then it will check whether the two arguments contain the same data
If we use is then Python will check whether the two objects refer to the same object. The id() needs to be the same for both of the objects
what is PIP in python?
PIP is a Python package manager.
Use PIP to download packages: pip install package_name
how to check types in python?
if not isinstance(input, int):
Let’s assume your list contains a trillion records and you are required to count the number of even numbers from the list. It will not be optimum to load the entire list in the memory. You can instead yield each item from the list.
range(start, stop, step):
Generates numerical values that start at start, stop at stop with the provided steps. As an instance, to generate odd numbers from 1 to 9, do:
rint(list(range(1,10,2)))
what is tuples in python?
Tuples are like lists in the sense that they can store a sequence of objects. The objects, again, can be of any type.
Tuples are faster than lists.
These collections are indexed by integers.
Tuples are immutable (non-update-able)
my_tuple = tuple() or my_tuple = 'f','m' or my_tuple = ('f', 'm')
Print dictionary contents in python
for key in dictionary:
print key, dictionary[key]
get all items from dictionary in python?
dictionary.items() # returns items #checking if a key exists in a dictionary if ('some key' in dictionary): #do something
remove operations with dictionaries in python?
pop(key, default): returns value for key and deletes the item with key else returns default
popitem(): removes random item from the dictionary
merges two dictionaries in python
dictionary1.update(dictionary2)
what is zip in python
takes multiple collections and returns a new collection.
The new collection contains items where each item contains one element from each input collection.
It allows us to transverse multiple collections at the same time
name = ‘farhad’
suffix = [1,2,3,4,5,6]
zip(name, suffix)
–> returns (f,1),(a,2),(r,3),(h,4),(a,5),(d,6)
__str__ in python?
Returns stringified version of an object when we call “print”:
__cmp__
in python?
Use the __cmp__ instance function if we want to provide custom logic to compare two objects of the same instance.
It returns 1 (greater), -1 (lower) and 0 (equal) to indicate the equality of two objects.
Think of __cmp__ like Equals() method in other programming language.