ML / Python Flashcards

1
Q

Create array from array without reference [python]

A

a = b[:]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

how to declare a list and map? [python]

A
mp = {}
lst = []
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

How to check if the element is int or array? [python]

A
for v in data_list:
        if isinstance(v, int):
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Implement decorator which returns function signature and its return value

A
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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

How to remove the element from the list with the index? [python]

A

del lst[i]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

how to inherit class in Python?

A

class Shuttle(Rocket):

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

how to call super from child class?

A

super().__init__(name, mission)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What Is Python?

A

Interpreted high-level object-oriented dynamically-typed scripting language.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

python standard data types

A

numbers, strings, sets, lists, tuples, and dictionaries

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Can we update string in Python?

A

Strings are immutable. Once they are created, they cannot be changed e.g.
a = ‘me’
Updating it will fail:
a[1]=’y’

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What if we create variable in for-loop or if ??? [python]

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

how to use global variable in Python?

A
TestMode = True
def some_function():
  global TestMode
  TestMode = False
some_function()
print(TestMode)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

how to get type of variable in Python?

A

type(‘farhad’)

–> Returns

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

what is ‘divmod’ in python?

A

print(divmod(10,3)) #it will print 3 and 1 as 3*3 = 9 +1 = 10

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

repeat string in python

A

‘A’*3 will repeat A three times: AAA

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

how to reverse string in python?

A
x = 'abc'
x = x[::-1]
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

how to find index of second ‘a’ in a string? [python]

A
name = 'farhad'
index = name.find('a', 2) # finds index of second a
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

Regex uses in python for working with strings

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

how to cast variable to type in python?

A

str(x): To string
int(x): To integer
float(x): To floats

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

how to remove element from the set in Python?

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

how to get any element from the set in python?

A

set.pop() — returns any item from the set, raises KeyError if the set is empty

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

operations with sets in python?

A
a = {1,2,3}
b = {3,4,5}
c = a.intersection(b)
c = a.difference(b)
c = a.union(b)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

what is pickling in python?

A

Converting an object into a string and dumping the string into a binary file is known as pickling. The reverse is known as unpickling.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

If your function can take in any number of arguments - what to do in python?

A
then add a * in front of the parameter name:
def myfunc(*arguments):
  return a
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Q

what is **arguments in python?

A
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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
26
Q

how to use lambda in Python?

A

variable = lambda arguments: expression

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
27
Q

difference == vs is in python?

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
28
Q

what is PIP in python?

A

PIP is a Python package manager.

Use PIP to download packages: pip install package_name

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
29
Q

how to check types in python?

A

if not isinstance(input, int):

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
30
Q

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.

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
31
Q

what is tuples in python?

A

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')
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
32
Q

Print dictionary contents in python

A

for key in dictionary:

print key, dictionary[key]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
33
Q

get all items from dictionary in python?

A
dictionary.items() # returns items
#checking if a key exists in a dictionary
if ('some key' in dictionary):
  #do something
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
34
Q

remove operations with dictionaries in python?

A

pop(key, default): returns value for key and deletes the item with key else returns default
popitem(): removes random item from the dictionary

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
35
Q

merges two dictionaries in python

A

dictionary1.update(dictionary2)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
36
Q

what is zip in python

A

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)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
37
Q

__str__ in python?

A

Returns stringified version of an object when we call “print”:

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
38
Q

__cmp__

in python?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
39
Q

does python supports multiple inheritance?

A
Note: Python supports multiple inheritances unlike C#
class A(B,C):  #A implments B and C
40
Q

If you want to call parent class function then you can do: [python]

A

class A(B,C): #A implments B and C

super(A, self).function_name()

41
Q

what about garbage collection in python?

A

All of the objects in Python are stored in heap space. This space is accessible to the Python interpreter. It is private.
Python has an in-built garbage collection mechanism.

42
Q

Open a connection in sql and execute statement? [python]

A

import MySQLdb
database = MySQLdb.connect(“host”=”server”, “database-user”=”my username”, “password”=”my password”, “database-name”=”my database”)
cursor = database.cursor()

cursor. fetch(“Select * From MyTable”)
database. close()

43
Q

web services - to query a rest service in python

A

import requests
url = ‘http://myblog.com’
response = requests.get(url).text

44
Q

To Serialise and Deserialise JSON [python]

A
[deserialize]
import json
my_json = {"A":"1","B":"2"}
json_object = json.loads(my_json)
value_of_B = json_object["B"]

[serialize]
import json
a = “1”
json_a = json.dumps(a)

45
Q

how to insert values between indexes in python?

A

a[2:2] = [3, 4, 5, 6]

makes from 1 2 7 8 -> 1 2 3 4 5 6 7 8

46
Q

how to create a tuple with one element in python?

A

we can’t create a tuple with single element like (‘s’)

the correct answer is t = (‘foo’,)

47
Q

what we get (1, 2, 3, 4, 5, 6, 7, 8, 9)[1::3] in python?

A

(2, 5, 8)

48
Q

x = 5
y = -5
what we get in python from (y, x)[::-1] ?

A

(5, -5)

49
Q

parameters in split()? python

A

split() takes in two parameters: sep, the delimiter string, and maxsplit, which specifies the maximum number of splits to make on the input string.

50
Q

what is immutability in python strings mean?

A

strings can’t be changed

51
Q

function ord() in python

A

get ASCII code of character
»> print(ord(‘f’))
102

raises an exception in case trying to set string as parameter

52
Q

return Hello, my name is .’, with person inserted in place of . in python

A

return f’Hello, my name is {person}.’

53
Q

Note the difference between np.ndarray and np.array()

A

The former is an actual data type, while the latter is a function to make arrays from other data structures.

54
Q

How To Create a Pandas DataFrame

A

ata = np.array([[’’,’Col1’,’Col2’],
[‘Row1’,1,2],
[‘Row2’,3,4]])

print(pd.DataFrame(data=data[1:,1:],
index=data[1:,0],
columns=data[0,1:]))
you first select the values that are contained in the lists that start with Row1 and Row2, then you select the index or row numbers Row1 and Row2 and then the column names Col1 and Col2.

55
Q

how to get information about dataframe?

A

print(df.shape) - width and height
print(len(df.index)) - get height

output:
(2,3)
2

56
Q

how to get elements on the certain index in pandas?

A

A B C
0 1 2 3
1 4 5 6
2 7 8 9

# Using `iloc[]`
print(df.iloc[0][0])
# Using `loc[]`
print(df.loc[0]['A'])
# Using `at[]`
print(df.at[0,'A'])
# Using `iat[]`
print(df.iat[0,0])
57
Q

difference between .loc[] and .iloc[]

A

.loc[] works on labels of your index. This means that if you give in loc[2], you look for the values of your DataFrame that have an index labeled 2.
.iloc[] works on the positions in your index. This means that if you give in iloc[2], you look for the values of your DataFrame that are at index ’2`.

58
Q

Adding a Column to Your DataFrame

A

df = pd.DataFrame(data=np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]), columns=[‘A’, ‘B’, ‘C’])

# Use `.index`
df['D'] = df.index

D
0
1
2

59
Q

Resetting the Index of Your DataFrame

A

df_reset = df.reset_index(level=0, drop=True)

60
Q

remove the index name, if there is any, by executing [dataframe]

A

del df.index.name

61
Q

Deleting a Column from Your DataFrame

A

df.drop(‘A’, axis=1, inplace=True)

62
Q

Removing a Row from Your DataFrame

A

df. drop_duplicates([48], keep=’last’)

df. drop(df.index[1])

63
Q

How To Iterate Over a Pandas DataFrame

A

for index, row in df.iterrows() :

print(row[‘A’], row[‘B’])

64
Q

Output a DataFrame to CSV

A

import pandas as pd

df.to_csv(‘myDataFrame.csv’)

65
Q

drop rows with missing values

A

df.dropna()

66
Q

new dict with empty values from existing dict

A

D = dict.fromkeys(keys)

67
Q

sorted list of keys from dict in python

A

sorted(D.keys())

68
Q

value swapping in python

A

a, b = b, a

69
Q

Create a single string from all the elements in list [Python]

A

” “.join(a)

70
Q

Find The Most Frequent Value In A List [Python]

A
max(set(a), key=a.count))
or
from collections import Counter
cnt = Counter(a)
cnt.most_common(3)
71
Q

Chained function call in python

A

b - True
product and add - functions
(product if b else add)(5,7)

72
Q

Remove duplicates from a list in python

save order / and not

A

items = [2,3,4,5,6]
list(set(items))

from collections import OrderedDict
list(OrderedDict.fromkeys(items).keys())

73
Q

matrix product [numpy]

A

A - np.array()
A @ B
A.dot(B)

74
Q

[pandas] how to get dataframe from dictionaries and transpose it?

A

return pd.DataFrame.from_dict(data, orient=’index’, columns=labels).T

75
Q

what is the difference between np.array and np.asarray?

A

by default, np.array copies the objects

76
Q

how to get 3 biggest elements of the following array? [numpy

ar = np.array([2,2,2,2,23,4,5,5,6])

A
77
Q

how to save NumPy array in a file

A

np.savetxt(‘foo.csv’,arr, delimiter=’,’)

78
Q

suppose you want to join train and test dataset (both are two numpy arrays train_set and test_set) into a reshaping array (resulting_ste) to do data processing on it simultaneously.

A

resulting_set = np.vstack([train_set, test_test])

79
Q

what is supervised learning?

A

we are given a data set and already know what our correct output should look like, having the idea that there is a relationship between input and output

80
Q

what is unsupervised learning?

A

allows us to approach a problem with continious predict in a what our results should look like

81
Q

supervised learning - 2 types?

A

regression and classification

82
Q

gradient descent algorithms

A

theta := theta - alpha * disc( J(theta(s))

83
Q

what is convex function?

A

only one global minimum

84
Q

formula of gradient descent

A

… check 2nd page of notes

85
Q

what is feature scaling?

A

replace xi with xi - mi to make features have approximately zero mean (do no apply to x0)

86
Q

how to choose learning rate alpha?

A

0.001 0.003 0.01 0.03 0.1 0.3 1 …

declare convergence if J decreases by less that 10^-3

87
Q

how to improve out features?

A
  • combine different features into one

- change the begav of the curve by making it quadratic, cubic, squares

88
Q

“high bias” what is it?

A

underfit

89
Q

“high variance”

A

overfit

90
Q

what is regularization?

A

J = J + lambda * sum ( theta.^2)

91
Q

Effective K-Means Algorithm

A
92
Q

how to choose number of clusters?

A

Elbow method

93
Q

What is PCA?

A

PCA is a technique used to reduce the number of dimensions in a dataset while preserving the most important information in it

94
Q

What is enumerate in Python?

A

(0, “d”), (1, “d”) -> enumerate(list)

95
Q

what is hyperparameter tuning?

A

the process to find the most optimal hyperparameters to avoid overfitting or underfitting.

96
Q

What if we inherited 2 classes in Python and they have the same methods?

A

MRO - Method Resolution Order

Three (One, Two) -> so we firstly take method from Three, then One and then Two