Formulae - Programing
Formulae - Programing
Excel
SEQUENCE
1.1. Formulas RANDARRAY
https://exceljet.net/formulas
https://xlncad.com/textsplit-and-13-new-functions-in-excel/
(crietria1)*(criteria2) // AND TEXTJOIN()
(crietria1)+(criteria2) // OR TEXTSPLIT(B5;{“ “;”_”;”-“;”,”})
TEXTBEFORE(B5,"_") // left side
XLOOKUP(1,(B5:B15=H5)*(C5:C15=H6)*(D5:D15=H7),E5:E15) TEXTAFTER(B5,"_") // right side
INDEX(E5:E15,MATCH(1,(B5:B15=H5)*(C5:C15=H6)*(D5:D15=H7),0))
INDEX //to choose column of spill range https://stackoverflow.com/questions/59474792/cumulative-sum-formula-
using-new-excel-dynamic-array-formulas
INDIRECT(ADDRESS()) SCAN(0;A1#;LAMBDA(x;y;x+y)) // cum sum
CHOOSE LET(x;A1:A8;sum;LAMBDA(z;y;z+y);SCAN(0;x;sum))
RANK MAP(A1:A8;LAMBDA(x;SUM(A1:x)))
SMALL
LARGE VSTACK
HSTACK
SIN(RADIANS(45)) TOCOL
SUM(Sheet1:Sheet3!A1) TOROW
WRAPCOLS
SUMIF(Nomes;Unique(Nomes);Valores) WRAPROWS
1
2. Python
2.1. Python Language & Syntax Cheat 2.1.7. Loops
Warning: Use the 4 spaces rule!!! (Indentation)
Sheet for i in range(1,10): #using a range
https://www.interviewbit.com/blog/python-commands/ print i
https://www.tutorialspoint.com/python/python_basic_syntax.htm for i in [1, 3, 5, 7]: #using a list
https://www.101computing.net/wp/wp-content/uploads/Python-Cheat- print i
Sheet.pdf
Rule #1: Python is white-space dependent; code blocks are indented i=0
using spaces. while i<=100:
Rule #2: Python language is case sensitive. It matters for variables, print i
functions and any keyword in general. #When using a loop, if you want to exit the loop you can use the following
instruction:
Python Integrated Development Environments (IDE): (e.g.: Spyder, break # Ends loop prematurely
VSCode, PyCharm, Eclipse, The Jupyter Notebook, AWS Cloud9, Wing 2.1.8. Comparison Operators & Conditions
Python IDE, Selenium IDE, Kite, Codeanywhere, Summary) #These operators can be used in If Statements or with While loops. They
2.1.1. Variable Assignment return True or False!
myInteger = 1 a == b Is a equal to b?
myString = “Hello World” a != b Is a different from b?
myList = [ “John”, “James”, “Laura” ] a<b Is a lower than b?
array=list(range(0,10)) a>b Is a greater than b?
playerName = input ( “What’s your name?” ) a <= b Is a lower or equal to b?
a >= b Is a greater or equal to b?
2.1.2. Adding Comments / Annotations a is None Is a null/none?
# Single Line Comment a is not None Is a not null/none?
""" a in [“John”,”James”,”Luke”] Is a one of the value in the given list?
Multi-line comment myString.startswith("Hello") Does myString start with the string “Hello”?
""" “@” in myEmail Does the string myEmail contains the string
2.1.3. Conversions “@”?
str(100) #To convert from a numeric type to a string:
int("100") #To convert from a string to an integer: 2.1.9. Importing Modules
float("100.5") #To convert from a string to a float: # Imports should be made at the top of your code: #e.g.
myAge= int ( input( “What’s Your Age” ) ) #e.g import pandas as pd
import random
Grouped_result=df.groupby(['Result'])
df = pd.DataFrame({'lookup_array': [0, 1, 2, 3, 4],
Grouped_result.get_group('Result 1')
'return_array': ['a', 'b', 'c', 'd', 'e']})
#print(xlookup(3, df["lookup_array"], df["return_array"]))
Filter=df.[ 'Result']== 'Result 1'
df.loc[Filter] a=[]
for i in range(0,len(df["return_array"])):
result=xlookup(i, df["lookup_array"], df["return_array"])
Localize values a.append(result)
https://www.geeksforgeeks.org/selecting-rows-in-pandas-dataframe- print(a)
based-on-conditions/
z=Array.loc[Array[“columnA”]=="10"]
print(z) https://stackoverflow.com/questions/46207292/pandas-vlookup-against-
REPLACE series-with-common-index-using-map
https://appdividend.com/2022/03/15/python-list-replace/ import pandas as pd
for i in range(len(column1)):
if column1 [i] <= 3: data = { "id":{"0":"K69","1":"K70","2":"K71","3":"K72","4":"K73"},
column1 [i] ="CDN" "cost":{"0":29.74,"1":9.42,"2":9.42,"3":9.42,"4":9.48 },
elif column1 [i] >= 5 and column1 [i] <= 8: "mark_up_id":{"0":"123","1":"456","2":"789","3":"111","4":"222"}}
column1 [i] = "CDM" df = pd.DataFrame(data=data)
print(column1) print(df)
////////////////OR//////////////// pb = {"mark_up_id":{"0":"123","1":"456","2":"789","3":"111","4":"222"},
dataset["column1"]=dataset["column1"].replace([1,2,3],["A","B","C"]) "mark_up":{"0":1.2987,"1":1.5625,"2":1.3698,"3":1.3333,"4":1.4589}}
pb = pd.DataFrame(data=pb).set_index('mark_up_id')
////////////////OR//////////////// print(pb)
df = pd.DataFrame({'A': [0, 1, 2, 3, 4],
'FREGUESIA': ['a', 'b', 'c', 'd', 'e'], #df = df.assign(price=df['mark_up_id'].map(pb['mark_up']) *
df['cost']).dropna()
'C': ['a', 'b', 'c', 'd', 'e']})
df = df.assign(price=df['mark_up_id'].map(pb['mark_up']) * df['cost'])
print(df)
df = pd.DataFrame({'FREGUESIA': ['a', 'b', 'c', 'd', 'e']})
////////////////OR////////////////
df=pd.DataFrame(df, columns=["FREGUESIA"])
import pandas as pd
data = { "Freg":[10,12,13,14,15,16],
init = ["b","c","e"]
"Zona":["I","I","II","II","III","III"]}
final = [17,16,19]
df = pd.DataFrame(data=data)
print(df)
print(df)
print(init)
print(final)
ref = {"Zona":["I","II","III"], "valor":[830,725,657.3]}
df["FREGUESIA"].replace(init,final,inplace=True)
ref = pd.DataFrame(data=ref).set_index('Zona')
df["FREGUESIA"]=df["FREGUESIA"].replace(init,final,inplace=True)
print(ref)
print(df)
df = df.assign(valor=df['Zona'].map(ref['valor']))
4
print(df) exposure.to_csv('New_file.csv', header=True, index=False, sep=';',
encoding = "ISO-8859-1").astype(str)
RENAME
new= pd.DataFrame(dataset, columns=["A","B"]).rename(columns = 2.2.4. Anaconda
{"B":"new_column"}) 2.2.5. Spyder
FILTER by length
df[df['A'].map(len) == 6] 2.3. Cheat Sheets for Programmers
https://enoumen.com/wp-content/uploads/2021/04/beginners-python-
df[df['amp'].str.len() == 6]
cheat-sheets.pdf
https://blog.finxter.com/pdf-cheat-sheets-for-programmers/
UNIQUE
import pandas as pd
# function to get unique values
def unique(list1):
unique_list = pd.Series(list1).drop_duplicates().tolist()
for x in unique_list:
print(x)
////////////////OR////////////////
dataset_new=dataset.drop_duplicates(subset=["","","",""])
s1 = s3.split("_")
TRANSPOSE
https://datagy.io/python-transpose-list-of-lists/
transposed = pd.array(list1).T.tolist()
print(transposed)
Flatten list
flatten_list = [i for s in list_of_lists for i in s]
Column Names
https://sparkbyexamples.com/pandas/pandas-get-column-names/
column_names = list(df.columns.values) # Get the list of all column
names from headers
column_names = df.columns.values.tolist() # Get the list of all column
names from headers
column_names = list(df.columns)#Using list(df) to get the column headers
as a list
column_names = list(df) #Using list(df) to get the list of all Column
Names
column_names=sorted(df) # Dataframe show all columns sorted list
df.columns.get_loc("TITULO_DA_COLUNA")
Selected_Columns=pd.DataFrame(dataset,columns=["FREGUESIA","ESTRU
TURA","ESNPAV","T EDIF C2011 EPOCA_EPOCA"])
IMPORT
f = pd.read_csv(file,header=None,names=[“A”,”B”,”C”])
EXPORT
column_names = ["A","B","C"]
exposure=pd.DataFrame(new,columns=column_names).sort_values(["A"],
ascending=[True])
5
6
7
8
2.4. LinkedIn quiz
## Python (Programming Language)
- [ ] An abstract class is the name for any class from which you can
instantiate an object.
- [ ] Abstract classes must be redefined any time an object is instantiated
from them.
- [ ] Abstract classes must inherit from concrete classes.
- [x] An abstract class exists only so that other "concrete" classes can
inherit from the abstract class.
[reference](https://www.geeksforgeeks.org/abstract-classes-in-python/)
#### Q2. What happens when you use the build-in function `any()` on a
list?
- [ ] The `any()` function will randomly return any item from the list.
- [x] The `any()` function returns True if any item in the list evaluates to
True. Otherwise, it returns False.
- [ ] The `any()` function takes as arguments the list to check inside, and
the item to check for. If "any" of the items in the list match the item to
check for, the function returns True.
- [ ] The `any()` function returns a Boolean value that answers the question
"Are there any items in this list?"
**example**
```python
if any([True, False, False, False]) == True:
print('Yes, there is True')
>>> 'Yes, there is True'
```
#### Q3. What data structure does a binary tree degenerate to if it isn't
balanced properly?
9
[reference](https://www.scaler.com/topics/linked-list/) - [ ] `def Game.LogicGame(): pass`
- [ ] `class Game.LogicGame(): pass`
#### Q4. What statement about static methods is true?
**Explanation:** `The parent class which is inherited is passed as an
- [ ] Static methods are called static because they always return `None`. argument to the child class. Therefore, here the first option is the right
- [ ] Static methods can be bound to either a class or an instance of a class. answer.`
- [x] Static methods serve mostly as utility methods or helper methods,
since they can't access or modify a class's state. #### Q11. What is the correct way to write a doctest?
- [ ] Static methods can access and modify the state of a class or an
instance of a class. -[]A
[reference](https://www.geeksforgeeks.org/class-method-vs-static- ```python
method-python) def sum(a, b):
"""
#### Q5. What are attributes? sum(4, 3)
7
- [ ] Attributes are long-form version of an `if/else` statement, used when
testing for equality between objects. sum(-4, 5)
- [x] Attributes are a way to hold data or describe a state for a class or an 1
instance of a class. """
- [ ] Attributes are strings that describe characteristics of a class. return a + b
- [ ] Function arguments are called "attributes" in the context of class ```
methods and instance methods.
- [x] B
**Explanation** `Attributes defined under the class, arguments goes
under the functions. arguments usually refer as parameter, whereas ```python
attributes are the constructor of the class or an instance of a class.` def sum(a, b):
"""
#### Q6. What is the term to describe this code? >>> sum(4, 3)
`count, fruit, price = (2, 'apple', 3.5)` 7
#### Q8. What is one of the most common use of Python's sys library? ```python
def sum(a, b):
- [x] to capture command-line arguments given at a file's runtime ###
- [ ] to connect various systems, such as connecting a web front end, an >>> sum(4, 3)
API service, a database, and a mobile app 7
- [ ] to take a snapshot of all the packages and libraries in your virtual
environment >>> sum(-4, 5)
- [ ] to scan the health of your Python ecosystem while inside a virtual 1
environment ###
return a + b
[reference](https://www.scaler.com/topics/python-libraries/) ```
#### Q9. What is the runtime of accessing a value in a dictionary by using **Explanation** - use `'''` to start the doc and add output of the cell after
its key? `>>>`
- [ ] O(n), also called linear time. #### Q12. What built-in Python data type is commonly used to represent a
- [ ] O(log n), also called logarithmic time. stack?
- [ ] O(n^2), also called quadratic time.
- [x] O(1), also called constant time. - [ ] `set`
- [x] `list`
#### Q10. What is the correct syntax for defining a class called Game, if it - [ ] `None`
inherits from a parent class called LogicGame? - [ ] `dictionary`
- [ ] `You can only build a stack from scratch.`
- [x] `class Game(LogicGame): pass`
- [ ] `def Game(LogicGame): pass` #### Q13. What would this expression return?
10
- [ ] It runs one chunk of code if all the imports were successful, and
```python another chunk of code if the imports were not successful.
college_years = ['Freshman', 'Sophomore', 'Junior', 'Senior'] - [x] It executes one chunk of code if a condition is true, but a different
return list(enumerate(college_years, 2019)) chunk of code if the condition is false.
``` - [ ] It tells the computer which chunk of code to run if the is enough
memory to handle it, and which chunk of code to run if there is not
- [ ] `[('Freshman', 2019), ('Sophomore', 2020), ('Junior', 2021), ('Senior', enough memory to handle it.
2022)]`
- [ ] `[(2019, 2020, 2021, 2022), ('Freshman', 'Sophomore', 'Junior', [Reference](https://www.scaler.com/topics/python/python-if-else-
'Senior')]` statement/)
- [ ] `[('Freshman', 'Sophomore', 'Junior', 'Senior'), (2019, 2020, 2021,
2022)]` #### Q19. What built-in Python data type is best suited for implementing a
- [x] `[(2019, 'Freshman'), (2020, 'Sophomore'), (2021, 'Junior'), (2022, queue?
'Senior')]`
- [ ] dictionary
#### Q14. What is the purpose of the "self" keyword when defining or - [ ] set
calling instance methods? - [ ] None. You can only build a queue from scratch.
- [x] list
- [ ] `self` means that no other arguments are required to be passed into
the method. #### Q20. What is the correct syntax for instantiating a new object of the
- [ ] There is no real purpose for the `self` method; it's just historic type Game?
computer science jargon that Python keeps to stay consistent with other
programming languages. - [ ] `my_game = class.Game()`
- [x] `self` refers to the instance whose method was called. - [ ] `my_game = class(Game)`
- [ ] `self` refers to the class that was inherited from to create the object - [x] `my_game = Game()`
using `self`. - [ ] `my_game = Game.create()`
**Simple example** #### Q21. What does the built-in `map()` function do?
#### Q16. What is an instance method? - [ ] The function will return a RuntimeError if you don't return a value.
- [x] If the return keyword is absent, the function will return `None`.
- [x] Instance methods can modify the state of an instance or the state of - [ ] If the return keyword is absent, the function will return `True`.
its parent class. - [ ] The function will enter an infinite loop because it won't know when to
- [ ] Instance methods hold data related to the instance. stop executing its code.
- [ ] An instance method is any class method that doesn't take any
arguments. #### Q23. What is the purpose of the `pass` statement in Python?
- [ ] An instance method is a regular function that belongs to a class, but it
must return `None`. - [ ] It is used to skip the `yield` statement of a generator and return a
value of None.
#### Q17. Which statement does NOT describe the object-oriented - [x] It is a null operation used mainly as a placeholder in functions, classes,
programming concept of encapsulation? etc.
- [ ] It is used to pass control from one statement block to another.
- [ ] It protects the data from outside interference. - [ ] It is used to skip the rest of a `while` or `for loop` and return to the
- [ ] A parent class is encapsulated and no data from the parent class start of the loop.
passes on to the child class.
- [ ] It keeps data and the methods that can manipulate that data in one #### Q24. What is the term used to describe items that may be passed
place. into a function?
- [x] It only allows the data to be changed by methods.
- [x] arguments
[Reference](https://www.scaler.com/topics/python/encapsulation-in- - [ ] paradigms
python/) - [ ] attributes
- [ ] decorators
#### Q18. What is the purpose of an if/else statement?
#### Q25. Which collection type is used to associate values with unique
- [ ] It tells the computer which chunk of code to run if the instructions you keys?
coded are incorrect.
11
- [ ] `slot` ('Oranges', 3, 2.25),
- [x] `dictionary` ('Bananas', 4, 0.89)
- [ ] `queue` ]
- [ ] `sorted list` ```
-[]A #### Q30. What is the correct syntax for calling an instance method on a
class named Game?
```python
output = [] _(Answer format may vary. Game and roll (or dice_roll) should each be
called with no parameters.)_
fruit_tuple_0 = (first[0], quantities[0], price[0])
output.append(fruit_tuple) - [x] A
>>> [ - [ ] backtracking
('Apples', 5, 1.50), - [ ] dynamic programming
12
- [ ] decrease and conquer
- [x] divide and conquer ```python
a123
#### Q32. What is runtime complexity of the list's built-in `.append()` b123
method? c123
```
- [x] O(1), also called constant time
- [ ] O(log n), also called logarithmic time #### Q36. Pick correct representation of doctest for function in Python.
- [ ] O(n^2), also called quadratic time
- [ ] O(n), also called linear time -[]:
#### Q33. What is key difference between a `set` and a `list`? ```python
def sum(a, b):
- [ ] A set is an ordered collection unique items. A list is an unordered #a=1
collection of non-unique items. #b=2
- [ ] Elements can be retrieved from a list but they cannot be retrieved # sum(a, b) = 3
from a set.
- [ ] A set is an ordered collection of non-unique items. A list is an return a + b
unordered collection of unique items. ```
- [x] A set is an unordered collection unique items. A list is an ordered
collection of non-unique items. -[]:
#### Q41. What value would be returned by this check for equality? #### Q47. What statement about the class methods is true?
#### Q52. What is the correct syntax for creating a variable that is bound #### Q57. What is the most self-descriptive way to define a function that
to a set? calculates sales tax on a purchase?
```python - [x] :
class __init__():
pass ```python
``` def calculate_sales_tax(subtotal):
pass
- [x] : ```
```python #### Q58. What would happen if you did not alter the state of the element
def __init__(self): that an algorithm is operating on recursively?
pass
``` - [ ] You do not have to alter the state of the element the algorithm is
recursing on.
#### Q54. Which of the following is TRUE About how numeric data would - [ ] You would eventually get a KeyError when the recursive portion of the
be organised in a Binary Search Tree? code ran out of items to recurse on.
- [x] You would get a RuntimeError: maximum recursion depth exceeded.
- [x] For any given node in a binary search tree, the value of the node is - [ ] The function using recursion would return None.
greater than all the values in the node's left subtree and less than the ones
in its right subtree. [explanation](https://www.python-course.eu/
- [ ] Binary Search Tree cannot be used to organize and search through python3_recursive_functions.php#Definition-of-Recursion)
numeric data, given the complication that arise with very deep trees.
15
#### Q59. What is the runtime complexity of searching for an item in a - [x] Virtual environments create a "bubble" around your project so that
binary search tree? any libraries or packages you install within it don't affect your entire
machine.
- [ ] The runtime for searching in a binary search tree is O(1) because each - [ ] Teams with remote employees use virtual environments so they can
node acts as a key, similar to a dictionary. share code, do code reviews, and collaborate remotely.
- [ ] The runtime for searching in a binary search tree is O(n!) because - [ ] Virtual environments were common in Python 2 because they
every node must be compared to every other node. augmented missing features in the language. Virtual environments are not
- [x] The runtime for searching in a binary search tree is generally O(h), necessary in Python 3 due to advancements in the language.
where h is the height of the tree. - [ ] Virtual environments are tied to your GitHub or Bitbucket account,
- [ ] The runtime for searching in a binary search tree is O(n) because every allowing you to access any of your repos virtually from any machine.
node in the tree must be visited.
#### Q66. What is the correct way to run all the doctests in a given file
[explanation](https://www.geeksforgeeks.org/binary-search-tree-data- from the command line?
structure/)
- [x] `python3 -m doctest <_filename_>`
#### Q60. Why would you use `mixin`? - [ ] `python3 <_filename_>`
- [ ] `python3 <_filename_> rundoctests`
- [ ] You use a `mixin` to force a function to accept an argument at runtime - [ ] `python3 doctest`
even if the argument wasn't included in the function's definition.
- [ ] You use a `mixin` to allow a decorator to accept keyword arguments. [tutorial video](https://www.youtube.com/watch?
- [ ] You use a `mixin` to make sure that a class's attributes and methods v=P8qm0VAbbww&t=180s)
don't interfere with global variables and functions.
- [x] If you have many classes that all need to have the same functionality, #### Q67. What is a lambda function ?
you'd use a `mixin` to define that functionality.
- [ ] any function that makes use of scientific or mathematical constants,
[explanation](https://www.youtube.com/watch?v=zVFLBfqV-q0) often represented by Greek letters in academic writing
- [ ] a function that get executed when decorators are used
#### Q61. What is the runtime complexity of adding an item to a stack and - [ ] any function whose definition is contained within five lines of code or
removing an item from a stack? fewer
- [x] a small, anonymous function that can take any number of arguments
- [ ] Add items to a stack in O(1) time and remove items from a stack on but has only expression to evaluate
O(n) time.
- [x] Add items to a stack in O(1) time and remove items from a stack in [Reference](https://www.guru99.com/python-lambda-function.html)
O(1) time.
- [ ] Add items to a stack in O(n) time and remove items from a stack on **Explanation:**
O(1) time.
- [ ] Add items to a stack in O(n) time and remove items from a stack on > The lambda notation is basically an anonymous function that can take
O(n) time. any number of arguments with only single expression (i.e, cannot be
overloaded). It has been introducted in other programming languages,
#### Q62. Which statement accurately describes how items are added to such as C++ and Java. The lambda notation allows programmers to
and removed from a stack? "bypass" function declaration.
- [ ] a stacks adds items to one side and removes items from the other side. #### Q68. What is the primary difference between lists and tuples?
- [x] a stacks adds items to the top and removes items from the top.
- [ ] a stacks adds items to the top and removes items from anywhere in - [ ] You can access a specific element in a list by indexing to its position,
the stack. but you cannot access a specific element in a tuple unless you iterate
- [ ] a stacks adds items to either end and removes items from either end. through the tuple
- [x] Lists are mutable, meaning you can change the data that is inside
**Explanation** Stack uses the _last in first out_ approach them at any time. Tuples are immutable, meaning you cannot change the
data that is inside them once you have created the tuple.
#### Q63. What is a base case in a recursive function? - [ ] Lists are immutable, meaning you cannot change the data that is inside
them once you have created the list. Tuples are mutable, meaning you can
- [x] A base case is the condition that allows the algorithm to stop change the data that is inside them at any time.
recursing. It is usually a problem that is small enough to solve directly. - [ ] Lists can hold several data types inside them at once, but tuples can
- [ ] The base case is summary of the overall problem that needs to be only hold the same data type if multiple elements are present.
solved.
- [ ] The base case is passed in as an argument to a function whose body #### Q69. What does a generator return?
makes use of recursion.
- [ ] The base case is similar to a base class, in that it can be inherited by - [ ] None
another object. - [x] An iterable object
- [ ] A linked list data structure from a non-empty list
#### Q64. Why is it considered good practice to open a file from within a - [ ] All the keys of the given dictionary
Python script by using the `with` keyword?
#### Q70. What is the difference between class attributes and instance
- [ ] The `with` keyword lets you choose which application to open the file attributes?
in.
- [ ] The `with` keyword acts like a `for` loop, and lets you access each line - [ ] Instance attributes can be changed, but class attributes cannot be
in the file one by one. changed
- [ ] There is no benefit to using the `with` keyword for opening a file in - [x] Class attributes are shared by all instances of the class. Instance
Python. attributes may be unique to just that instance
- [x] When you open a file using the `with` keyword in Python, Python will - [ ] There is no difference between class attributes and instance attributes
make sure the file gets closed, even if an exception or error is thrown. - [ ] Class attributes belong just to the class, not to instance of that class.
Instance attributes are shared among all instances of a class
[explanation](https://docs.python.org/3/tutorial/
inputoutput.html#reading-and-writing-files) #### Q71. What is the correct syntax of creating an instance method?
16
```python
def get_next_card(): if num_people > 10:
# method body goes here print("There is a lot of people in the pool.")
``` elif num_people > 4:
print("There are some people in the pool.")
- [x] : else:
print("There is no one in the pool.")
```python ```
def get_next_card(self):
# method body goes here -[]:
```
```python
-[]: num_people = 5
- [ ] `orange = my_list[1]` - [ ] `defaultdict` will automatically create a dictionary for you that has keys
- [x] `my_list[1] = 'orange'` which are the integers 0-10.
- [ ] `my_list['orange'] = 1` - [ ] `defaultdict` forces a dictionary to only accept keys that are of the
- [ ] `my_list[1] == orange` types specified when you created the `defaultdict` (such as strings or
integers).
#### Q75. What will happen if you use a while loop and forget to include - [x] If you try to read from a `defaultdict` with a nonexistent key, a new
logic that eventually causes the while loop to stop? default key-value pair will be created for you instead of throwing a
`KeyError`.
- [ ] Nothing will happen; your computer knows when to stop running the - [ ] `defaultdict` stores a copy of a dictionary in memory that you can
code in the while loop. default to if the original gets unintentionally modified.
- [ ] You will get a KeyError.
- [x] Your code will get stuck in an infinite loop. #### Q79. What is the correct syntax for adding a key called `variety` to
- [ ] You will get a WhileLoopError. the `fruit_info` dictionary that has a value of `Red Delicious`?
-[]: - [ ] It returns a 5x5 matric; each row will have the values 1,2,3,4,5.
- [ ] It returns an array with the values 1,2,3,4,5
```python - [ ] It returns five different square matrices filled with ones. The first is
def __init__(attr1, attr2): 1x1, the second 2x2, and so on to 5x5
self.attr1 = attr1 - [x] It returns a 5-dimensional array of size 1x2x3x4x5 filled with 1s.
self.attr2 = attr2
``` [Reference](https://www.geeksforgeeks.org/numpy-ones-python/)
**Explanation**: When instantiating a new object from a given class, the #### Q85. You encounter a FileNotFoundException while using just the
`__init__()` method will take both `attr1` and `attr2`, and set its values to filename in the `open` function. What might be the easiest solution?
their corresponding object attribute, that's why the need of using
`self.attr1 = attr1` instead of `attr1 = attr1`. - [ ] Make sure the file is on the system PATH
- [ ] Create a symbolic link to allow better access to the file
#### Q82. What would this recursive function print if it is called with no - [x] Copy the file to the same directory as where the script is running from
parameters? - [ ] Add the path to the file to the PYTHONPATH environment variable
```python #### Q87. What does the // operator in Python 3 allow you to do?
1
1 - [x] Perform integer division
2 - [ ] Perform operations on exponents
2 - [ ] Find the remainder of a division operation
3 - [ ] Perform floating point division
3
``` #### Q88. What file is imported to use dates in python?
```python -[]:
z = y.split(';')
len(z) ```python
``` y = [x*2 for x in range(1,10)]
print(y)
- [ ] 17 ```
- [x] 4
-[]0 -[]:
-[]3
```python
**Explanation**: y=1
for i in range(1,10):
```python y=y*2
y="stuff;thing;junk" print(y)
len(z) ==> 3 ```
y="stuff;thing;junk;" [Reference](https://www.digitalocean.com/community/tutorials/how-to-
len(z) ==> 4 do-math-in-python-3-with-operators#:~:text=The%20**%20operator
``` %20in%20Python,multiplied%20by%20itself%203%20times.)
#### Q93. What is the output of this code? #### Q96. Elements surrounded by `[]` are **\_**, `{}` are **\_**, and `()`
are **\_**.
```python
num_list = [1,2,3,4,5] - [ ] sets only; lists or dictionaries; tuples
num_list.remove(2) - [ ] lists; sets only; tuples
print(num_list) - [ ] tuples; sets or lists; dictionaries
``` - [x] lists; dictionaries or sets; tuples
- [ ] `[1,2,4,5]` [Reference](https://www.geeksforgeeks.org/differences-and-applications-
- [x] `[1,3,4,5]` of-list-tuple-set-and-dictionary-in-python/)
- [ ] `[3,4,5]`
- [ ] `[1,2,3]` #### Q97. What is the output of this code? (NumPy has been imported as
np.)
**Explanation**: `.remove()` is based on the value of the item, not the
index; here, it is removing the item matching "2". If you wanted to remove ```python
an item based on its index, you would use `.pop()`. table = np.array([
[1,3],
```python [2,4]])
num_list = [1,2,3,4,5] print(table.max(axis=1))
```
num_list.pop(2)
>>> [1,2,4,5] - [ ] `[2, 4]`
- [x] `[3, 4]`
num_list.remove(2) - [ ] `[4]`
>>> [1,3,4,5] - [ ] `[1,2]`
```
19
[Reference](https://colab.research.google.com/drive/ ```python
1PRGf7Wgcr_gQk7snnxxuc5rL9O1ky9Xg?usp=sharing) letters = []
#### Q98. What will this code print? for letter in my_dictionary.values():
letters.append(letter)
```python ```
number = 3
print (f"The number is {number}") - [ ] `letters = my_dictionary.keys()`
``` - [ ] `letters = [letter for (letter, number) in my_dictionary.items()]`
- [ ] `letters4 = list(my_dictionary)`
- [x] `The number is 3`
- [ ] `the number is 3` **Explanation:** The first one (the correct option) returns the list of the
- [ ] `THE NUMBER IS 3` values (the numbers). The rest of the options return a list of the keys.
- [ ] It throws a TypeError because the integer must be cast to a string.
#### Q105. When an array is large, NumPy will not print the entire array
[Reference](https://colab.research.google.com/drive/ when given the built-in `print` function. What function can you use within
1PRGf7Wgcr_gQk7snnxxuc5rL9O1ky9Xg?usp=sharing) NumPy to force it to print the entire array?
#### Q99. Which syntax correctly creates a variable that is bound to a - [ ] `set_printparams`
tuple? - [x] `set_printoptions`
- [ ] `set_fullprint`
- [ ] `my_tuple tup(2, 'apple', 3.5) %D` - [ ] `setp_printwhole`
- [ ] `my_tuple [2, 'apple', 3.5].tuple() %D`
- [x] `my_tuple = (2, 'apple', 3.5)` #### Q106. When would you use a try/except block in code?
- [ ] `my_tuple = [2, 'apple', 3.5]`
- [x] You use `try/except` blocks when you want to run some code, but
[Reference](https://beginnersbook.com/2018/02/python-tuple/) need a way to execute different code if an exception is raised.
- [ ] You use `try/except` blocks inside of unit tests so that the unit testes
#### Q100. Which mode is not a valid way to access a file from within a will always pass.
Python script? - [ ] You use `try/except` blocks so that you can demonstrate to your code
reviewers that you tried a new approach, but if the new approach is not
- [ ] `write('w')` what they were looking for, they can leave comments under the `except`
- [x] `scan('s')` keyword.
- [ ] `append('a')` - [ ] You use `try/except` blocks so that none of your functions or methods
- [ ] `read('r')` return `None`.
1. [Reference](https://docs.python.org/3/library/functions.html#open) [Reference](https://runestone.academy/ns/books/published/fopp/
2. [Reference](https://www.w3schools.com/python/ref_list_append.asp) Exceptions/using-exceptions.html#:~:text=The%20reason%20to%20use
%20try,you're%20writing%20the%20code)
#### Q101. NumPy allows you to multiply two arrays without a for loop.
This is an example of \_. #### Q107. In Python, how can the compiler identify the inner block of a
for loop?
- [x] vectorization
- [ ] attributions - [x] `because of the level of indentation after the for loop`
- [ ] accelaration - [ ] `because of the end keyword at the end of the for loop`
- [ ] functional programming - [ ] `because of the block is surrounded by brackets ({})`
- [ ] `because of the blank space at the end of the body of the for loop`
#### Q102. What built-in Python data type can be used as a hash table?
#### Q108. What Python mechanism is best suited for telling a user they
- [ ] `set` are using a deprecated function
- [ ] `list`
- [ ] `tuple` - [ ] sys.stdout
- [x] `dictionary` - [ ] traceback
- [x] warnings
#### Q103. Which Python function allows you to execute Linux shell - [ ] exceptions
commands in Python?
#### Q109. What will be the value of x after running this code?
- [ ] `sys.exc_info()`
- [x] `os.system()` ```python
- [ ] `os.getcwd()` x = {1,2,3,4,5}
- [ ] `sys.executable` x.add(5)
x.add(6)
#### Q104. Suppose you have the following code snippet and want to ```
extract a list with only the letters. Which fragment of code will \_not\_
achieve that goal? - [ ] `{1, 2, 3, 4, 5, 5, 6}`
- [ ] `{5, 6, 1, 2, 3, 4, 5, 6}`
```python - [ ] `{6, 1, 2, 3, 4, 5}`
my_dictionary = { - [x] `{1, 2, 3, 4, 5, 6}`
'A': 1,
'B': 2, **Explanation:** The `.add()` method adds the element to the set only if it
'C': 3, doesn't exist.
'D': 4,
'E': 5 #### Q110. How would you access and store all of the keys in this
} dictionary at once?
```
```python
- [x] <br> fruit_info = {
'fruit': 'apple',
20
'count': 2, d = sum(c)
'price': 3.5 ```
}
``` -[]B
```python #### Q115. What two functions within the NumPy library could you use to
a = np.zeros([3,4]) solve a system of linear equations?
b = a.copy()
np.array_equal(a,b) - [x] `linalg.eig() and .matmul()`
``` - [ ] `linalg.inv() and .dot()`
- [ ] `linalg.det() and .dot()`
-[]: - [ ] `linalg.inv() and .eye()`
#### Q114. In this code fragment, what will the values of c and d be **Explanation:** `//` is the operator for floor division, which is a normal
equivalent to? division operation that returns the largest possible integer, either less than
or equal to the normal division result. Here it is used to find the median,
```python which is the value separating the higher half from the lower half of a data
import numpy as np sample, by finding the index of the list item in the middle of the list. (This is
a = np.array([1,2,3]) sufficient for a list with an odd number of items; if the list had an even
b = np.array([4,5,6]) number of items, you would average the values of the two middle items to
c = a*b find the median value.)
d = np.dot(a,b)
``` #### Q118. What are the two main data structures in the Pandas library?
#### Q121. What is the output of this code? # example output : [("IronMan", "Downey"), ("Spider Man", "Holland"),
("Captain America", "Evans")]
```python ```
def myFunction(country = "France"):
print("Hello, I am from", country) - [ ] `[(x,y)] for x in characters for y in actors]`
- [x] `zip(characters, actors)`
myFunction("Spain") -[]
myFunction("")
myFunction() ```python
``` d = {}
-[]: ```python
{x : x*x for x in range(1,100)}
```python ```
Hello, I am from France
Hello, I am from France - [ ] a dictionary with x as a key, and x squared as its value; from 1 to 100
Hello, I am from France - [x] a dictionary with x as a key, and x squared as its value; from 1 to 99
``` - [ ] a set of tuples, consisting of (x, x squared); from 1 to 99
- [ ] a list with all numbers squared from 1 to 99
- [x] :
#### Q126. Jaccard Similarity is a formula that tells you how similar two
```python sets are. It is defined as the cardinality of the intersection divided by the
Hello, I am from Spain cardinality of the union. Which choice is an accurate implementation in
Hello, I am from Python?
Hello, I am from France
``` 
#### Q122. Choose the option below for which instance of the class #### Q127. Which choice is not a native numerical type in Python?
cannot be created
- [ ] Long
- [ ] Anonymous Class - [ ] Int
- [ ] Parent Class - [ ] Float
- [ ] Nested Class - [x] Double
- [x] Abstract Class
#### Q128. What will be the output of this code?
[Reference](https://www.scaler.com/topics/python/data-abstraction-in-
python/) ```python
22
[1,2,3] * 3 - [ ] The function will return a RuntimeError if you do not return a value.
``` - [x] If the return keyword is absent the function will return None.
- [ ] `[3,2,3]` #### Q136. it is often the case that the pandas library is used for **_ data
- [x] `[1, 2, 3, 1, 2, 3, 1, 2, 3]` and NumPy for _** data.
- [ ] You will get a type error.
- [ ] `[3,6,9]` - [x] string; numerical
- [ ] unstructured; structured
#### Q129. Given a list defined as numbers = `[1,2,3,4]`, what is the value - [ ] numerical; tabular
of `numbers[-2]`? - [ ] tabular; numerical
-[]1 [Reference](https://www.interviewbit.com/blog/pandas-vs-numpy/)
- [x] 3
-[]2 #### Q137. What do you need to do to install additional packages into
- [ ] An IndexError exception is thrown. Python?
#### Q130. Which statement about strings in Python is true? - [ ] Use a C compiler like gcc or clang.
- [x] Use a package manager like pip or conda.
- [x] Strings can be enclosed by double quotes (") or single quotes ('). - [ ] Use an IDE like Notepad++ or Idle.
- [ ] Strings can only be enclosed in single quotes ('). - [ ] Use a package manager like NPM or NuGet.
- [ ] Single character strings must be enclosed in single quotes ('), and the
rest must be enclosed in double quotes ("). #### Q138. The image below was created using Matplotlib. It is a
- [ ] Strings can only be enclosed in double quotes ("). distribution plot of a list of integers filled with numbers using the function
**\_** and plotted with **\_**.
#### Q131. What is the correct syntax for defining an _init_() method that
takes no parameters? 
#### Q132. Suppose you need to use the `sin` function from the `math` ```python
library. What is the correct syntax for importing only that function? import numpy as np
```python #### Q141. Assume you have a non-empty list named _mylist_ and you
print ("foo" if (256).bit_length() > 8 else "bar") want to search for a specific value. The minimum number of comparison
``` will be \_**_ and the maximum number of comparison will be _**?
#### Q144. Suppose you want to double-check if two matrices can be def introduce(self):
multipled using NumPy for debugging purposes. How would you complete print("My name is", self.name, "son of", self.fathername)
this code fragment by filling in the blanks with the appropiate variables?
- [ ] [(1, 2), (2, 3), (3, 4), (4, 5), (5, 6)] -[]:
- [ ] [1,2,3,4,5]
- [ ] [(1, 2), (2, 3), (3, 4)] ```python
- [x] [(1, 2), (2, 3), (3, 4), (4, 5)] class Father():
name = 'Robert'
#### Q146. In Python, a class method must have \_**\_ as a function
decorator, and the first parameter of the method will be a reference to \_\ class Person(Father):
_**. def __init__(self, name):
self.name = name
- [x] @classmethod; the class
- [ ] inline; the class def introduce(self):
- [ ] static; self print("My name is", self.name, "son of", base.name)
- [ ] @static; self
king = Person("Joffrey")
[Reference](https://docs.python.org/3/library/ king.introduce()
functions.html#classmethod)
```
#### Q147. Which snippet of code will print My name is Joffrey, son of
Robert? **Explanation:** In the first, super does not have .name (should be
self.name), The third drops Robert, and base is not defined in the 4th.
-[]:
#### Q148.
```python
class Father(): ```python
name = 'Robert' animals = {
'a': ['ant', 'antelope', 'armadillo'],
class Person(Father): 'b': ['beetle', 'bear', 'bat'],
def __init__(self, name): 'c': ['cat', 'cougar', 'camel']
self.fathername = super.name }
self.name = name
animals = defaultdict(list, animals)
def introduce(self):
print("My name is", self.name, "son of", self.fathername) print(animals['b'])
print(animals['d'])
king = Person("Joffrey") ```
24
- [x] matrix = vector.reshape(100,100)
- [x] A Exa
```python #### Q153. What will the value of the i variable be when the following
['beetle', 'bear', 'bat'] loop finishes its execution?
# an exception will be thrown
``` for i in range(5): pass
-[]C -[]5
- [ ] the variable becomes unavailable
```python -[]6
['beetle', 'bear', 'bat'] - [x] 4
None
``` #### Q154. f-strings are also called:
#### Q150. What does this code print in the console? [Reference](https://www.w3schools.com/python/python_conditions.asp)
```python **Explanation:** If you have only one statement to execute, one for `if`
x = 18 and one for `else`, you can put it all on the same line.
```python execution_fn()
x = 1j ```
print(x**2 == -1)
``` **Which of the following choices are the missing arguments?**
- [ ] a run-time error telling you that the variable `j` has not been initialized -[]:
- [x] True
- [ ] 1j ```
- [ ] False MISSING_ARG_1 = wrapper
**Explanation:** The letter `j` acts as the imaginary unit in Python, MISSING_ARG_2 = rval
therefore `x**2` means `j**2` which is equal to `-1`. The statement `x**2
== -1` is evaluated as `True`. MISSING_ARG_3 = func
```
#### Q164. What will be printed in the console if you run this code?
- [x] :
```python
print(0xA + 0xB + 0xC) ```
``` MISSING_ARG_1 = func
#### Q168. Which of the following statements defines a new object type **Explanation:** MRO stands for Method Resolution Order. It returns a
named "Dog" in Python? list of types the class is derived from, in the order they are searched for
methods.
- [x] class Dog:
- [ ] Dog class: #### Q176. Suppose you have a list of employees described by the code
- [ ] Dog: below. You want to assign alice the same salary as charlie. Which choice
- [ ] class Dog will accomplish that?
#### Q169. To use pipelines in scikit-learn, import from the scikit-learn.**\ ```python
_** submodule. employees = {
'alice':{
- [ ] preprocessing 'position':'Lead Developer',
- [x] pipeline 'salary':1000
- [ ] filters },
- [ ] pipe_filter 'bob':{
'position': 'Lead Artist',
#### Q170. You should pass in a value of **\_** for the axis argument to 'salary':2000
the Pandas apply method to apply the function to each row. },
'charlie':{
- [ ] row 'position':'cfo',
- [ ] col 'salary':3000
- [x] 1 }
-[]0 }
```
#### Q171. Data points in pyplot are called
- [x] `employess['alice']['salary'] = employees['charlie']['salary']`
- [ ] pointers - [ ] `employees.alice.salary = employees.charlie.salary`
- [ ] points - [ ] `employees['alice'][1] = employees['charlie'][1]`
- [x] markers - [ ] `employees['alice'].salary = employees['charlie'].salary`
- [ ] none of these
**Explanation:** This is accessing a key in a nested dictionary inside
#### Q172. What does this code print? another dictionary
28