You are on page 1of 28

1.

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

Trim() //remove spaces TAKE


DROP
1.2. Dynamic array formulas and CHOOSECOLS
CHOOSEROWS
spilled array behavior EXPAND
UNIQUE
SORT
SORTBY 1.3. Text
FILTER REPT(text; number of times)

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

2.1.4. String Manipulation import math


myString=”Hello “ + “world” import numpy
#The following code would return a list as follows: import pygame
[“John”,”James”,”Laura”]
2.1.10. Array Methods
myString=”John,James,Laura”
https://www.w3schools.com/python/python_arrays.asp
myString.split(“,”)
Method Description
#The following code would remove spaces at the #beginning and end of a
list.append(val) Adds an element at the end of the list
string
insert(6, 7)Adds an element at the specified position
myString=” Hello “
print( myString.strip() ) # this would display “Hello”
clear() Removes all the elements from the list
copy() Returns a copy of the list
2.1.5. Functions with parameters count() Returns the number of elements with the specified value
Warning: Use the 4 spaces rule!!! (Indentation) extend() Add the elements of a list (or any iterable), to the end of the
def myFunction ( arg1, arg2,… ) : current list
#Code goes here index() Returns the index of the first element with the specified value
return myValue pop([i]) Removes and returns the element at the ith position
remove() Removes the first item with the specified value
#e.g. reverse() Reverses the order of the list
def mySumFunction ( x, y, z=0 ) : sort() Sorts the list
sum = x + y + z
return sum
2.1.11. Operations
mySumFunction(1,2) #calling the fuction
list=[] defines an empty list
list[i]=a stores a at the ith position
2.1.6. IF Statements list[i] retrieves the character at the ith position
Warning: Use the 4 spaces rule!!! (Indentation) list[i:j] retrieves characters in the range I to j
if i == 7: [0] #1st
print “seven” [-1] #last
else: [1, 2, 3, 4, 5, 6, 7, 8, 9][1:-2] #cut arrays, result [2, 3, 4, 5, 6, 7]
print “Not seven!”
String[i] retrieves the character at the ith position
if i == 7: String[i:j] retrieves characters in the range I to j
print “seven”
elif i == 8: dict={} defines an empty dictionary
print “eight” dict[i]=a stores “a” to the key “i”
elif i == 9: dict[i] retrieves the item with the key “I”
print “nine” dict.key gives all the key items
else: dict.values gives all the values
print “Not seven, eight or nine”
print(f“string {variable}”)
2
Square brackets: [] [(0,0)] #means cell at 0,0 of your matrix
Lists and indexing/lookup/slicing [0:1] #means lines 0 to 1 excluded of your matrix
 Lists: [], [1, 2, 3], [i**2 for i in range(5)] [:1] #excluding the first value means all lines until line 1 excluded
[1:] #excluding the last param mean all lines starting form line 1
 Indexing: 'abc'[0] → 'a'
included
 Lookup: {0: 10}[0] → 10 [:] #excluding both means all lines
 Slicing: 'abc'[:2] → 'ab' [::2] #the addition of a second ':' is the sampling. (1 item every 2)
Parentheses: () (AKA "round brackets") [::] #exluding it means a sampling of 1
Tuples, order of operations, generator expressions, function calls and [:,:] #simply uses a tuple (a single , represents an empty tuple)
other syntax. instead
 Tuples: (), (1, 2, 3) of an index.
 Although tuples can be created without
parentheses: t = 1, 2 → (1, 2) 2.2.3. Panda in spyder
import pandas as pd
 Order of operations: (n-1)**2 print(pd.__version__) # Get pandas Version
 Generator expressions: (i**2 for i in range(5)) dataset = pd.read_csv('Filename.csv' , sep=';')
 Function or method calls: print(), int(), range(5), '1 2'.split(' ') sep='\t'
 with a generator expression: sum(i**2 for i in delimiter=';'
range(5)) skiprows=0
Curly braces: {} low_memory=False
Dictionaries and sets, as well as in string formatting encoding='utf-8' #acentuação
encoding = "ISO-8859-1"
 Dicts: {}, {0: 10}, {i: i**2 for i in range(5)} engine='python'
 Sets: {0}, {i**2 for i in range(5)} lineterminator='\\r'
 Except the empty set: set() header='infer'
 In string formatting to indicate replacement fields: header=True
index_col=False
 F-strings: f'{foobar}' index_col=”Column A”
 Format strings: '{}'.format(foobar) index=False
Regular expressions converters={"FREGUESIA DSG": str}
All of these brackets are also used in regex. Basically, [] are used for usecols=[“”,””,””]
character classes, () for grouping, and {} for repetition. converters={'ID': str}

Angle brackets: <> print(dataset.head(11)) #first n rows


Used when representing certain objects like functions, classes, and class
instances if the class doesn't override __repr__(), for example:
>>> print array = dataset_2011.values
<built-in function print> Freguesias=array[:,dataset_2011.columns.get_loc("FREGUESIA DSG")]
>>> zip
<class 'zip'>
>>> zip() sheet_to_df_map = pd.read_excel(file_name, sheet_name=None)
<zip object at 0x7f95df5a7340>
array = dataset.values
x=array[:,1:4] #[: (all lines) , 1:4 (columns 1 to 4)]
Print print(x)
df = pd.DataFrame({'FREGUESIA': ['a', 'b', 'c', 'd', 'e']})
print(df)
FREGUESIA JOIN ARRAYS
0 a https://pandas.pydata.org/docs/user_guide/merging.html
1 17
2 16 DF=pd.concat([df,df2,df3], axis=1)
3 d
4 19 drop(columns=[“A”])
print(list(df))
['FREGUESIA'] STACK
print(list(df["FREGUESIA"])) #List df_new=df.stack() #coluna única linha a linha
['a', 17, 16, 'd', 19] df_new=df.melt() # junta coluna a coluna

2.2. Packages https://pandas.pydata.org/docs/reference/api/


pandas.wide_to_long.html#pandas.wide_to_long
# df_new =df.drop(columns=[“A”]).stack()
2.2.1. Starting lines
df_new =pd.wide_to_long(df, stubnames=["H:"], i="A", j="B_new")
import os
print(df_new.unstack())
current_directory = os.getcwd()
print(current_directory)

os.chdir(r"C:\Users\GCL\OneDrive - Universidade de Aveiro\ SUMIFS


INVESTIG_Work in Progress\Assimilate project\Access 2011") # raw string https://stackoverflow.com/questions/58662447/trying-to-code-a-python-
equivalent-of-sumifs-feature-in-excel
https://www.statology.org/pandas-groupby-transform/
Shortcuts
https://stackoverflow.com/questions/48748804/sumifs-in-pandas-with-
two-conditions
Crt+R #replace variables
import pandas as pd
df = pd.DataFrame({'Sales': [100,110,200,300,150,200,100],
2.2.2. Numpy 'Origin': ['YYZ','YEA','CDG','YYZ','YEA','YVR','YEA'],
import numpy as np 'Dest': ['DEL','NYC','YUL','DEL','YTO','HKG','NYC']})
[0] #means line 0 of your matrix
3
df['Result'] = df.groupby(['Origin','Dest'])['Sales'].transform('sum') print(list(df))
print(list(df["FREGUESIA"]))
the operation (tranform) is applied to column (Series). Transform it's like
an aggregate function (e.g. .sum()), but the result is not applied to the
groups but to the individual rows, i.e. all rows of a group get the same ////////////////OR////////////////
result assigned
Result: # dictionary = {List_Freg_2011[i]: List_Freg_2021[i] for i in
Sales Origin Dest Result range(len(List_Freg_2021))}
0 100 YYZ DEL 400
# print(str(dictionary))
1 110 YEA NYC 210
2 200 CDG YUL 200 # for key in dictionary.keys():
3 300 YYZ DEL 400 # Freg_2011 = Freg_2011.replace(key, dictionary[key])
4 150 YEA YTO 150
5 200 YVR HKG 200
XLOOKUP
6 100 YEA NYC 210
https://pythoninoffice.com/replicate-excel-vlookup-hlookup-xlookup-in-
python/
Operations import pandas as pd
df['Result'] def xlookup(lookup_value, lookup_array, return_array, if_not_found:str =
.count() ''):
.value_counts() #conunts all unique options match_value = return_array.loc[lookup_array == lookup_value]
.value_counts(normalize=True) if match_value.empty:
.median() return f'"{lookup_value}" not found!' if if_not_found == '' else
.loc['Result 1'] if_not_found
.agg(['Result 1', 'Result 2']) else:
.str.contains('Word').sum() return match_value.tolist()[0]

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=["","","",""])

TEXTJOIN and SPLIT


for i in range(0,len(df["s1"])):
s3=str(df["s1"][i])+"_"+str(df["s2"][i])
print(s3)

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

for column_headers in df.columns:


print(column_headers) # Get all Column Header Labels as List
column_names = df.keys().values.tolist()
numeric_columns = df._get_numeric_data().columns.values.tolist()
# Get all numeric columns
numeric_columns=df.dtypes[df.dtypes == "int64"].index.values.tolist()
# Simple Pandas Numeric Columns Code

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)

#### Q1. What is an abstract class?

- [ ] 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?

- [x] linked list


- [ ] queue
- [ ] set
- [ ] OrderedDict

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

- [ ] `tuple assignment` >>> sum(-4, 5)


- [x] `tuple unpacking` 1
- [ ] `tuple matching` """
- [ ] `tuple duplication` return a + b
```
#### Q7. What built-in list method would you use to remove items from a
list? -[]C

- [ ] `.delete()` method ```python


- [ ] `pop(my_list)` def sum(a, b):
- [ ] `del(my_list)` """
- [x] `.pop()` method # >>> sum(4, 3)
#7
**example**
# >>> sum(-4, 5)
```python #1
my_list = [1,2,3] """
my_list.pop(0) return a + b
my_list ```
>>>[2,3]
``` -[]D

#### 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?

```python - [ ] It creates a path from multiple values in an iterable to a single value.


class my_secrets: - [x] It applies a function to each item in an iterable and returns the value
def __init__(self, password): of that function.
self.password = password - [ ] It converts a complex value type into simpler value types.
pass - [ ] It creates a mapping between two different elements of different
instance = my_secrets('1234') iterables.
instance.password
>>>'1234' **Explanation:** - The synax for `map()` function is
``` `list(map(function,iterable))`. The simple area finder using map would be
like this
#### Q15. Which of these is NOT a characteristic of namedtuples?
```python
- [ ] You can assign a name to each of the `namedtuple` members and refer import math
to them that way, similarly to how you would access keys in `dictionary`. radius = [1,2,3]
- [ ] Each member of a namedtuple object can be indexed to directly, just area = list(map(lambda x: round(math.pi*(x**2), 2), radius))
like in a regular `tuple`. area
- [ ] `namedtuples` are just as memory efficient as regular `tuples`. >>> [3.14, 12.57, 28.27]
- [x] No import is needed to use `namedtuples` because they are available ```
in the standard library.
#### Q22. If you don't explicitly return a value from a function, what
**We need to import it using**:`from collections import namedtuple` happens?

#### 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` ```

#### Q26. When does a for loop stop iterating? -[]D

- [ ] when it encounters an infinite loop ```python


- [ ] when it encounters an if/else statement that contains a break keyword i=0
- [x] when it has assessed each item in the iterable it is working on or a output = []
break keyword is encountered for fruit in fruits:
- [ ] when the runtime for the loop exceeds O(n^2) for qty in quantities:
for price in prices:
#### Q27. Assuming the node is in a singly linked list, what is the runtime output.append((fruit, qty, price))
complexity of searching for a specific node within a singly linked list? i += 1
return output
- [x] The runtime is O(n) because in the worst case, the node you are ```
searching for is the last node, and every node in the linked list must be
visited. #### Q29. What happens when you use the built-in function all() on a list?
- [ ] The runtime is O(nk), with n representing the number of nodes and k
representing the amount of time it takes to access each node in memory. - [ ] The `all()` function returns a Boolean value that answers the question
- [ ] The runtime cannot be determined unless you know how many nodes "Are all the items in this list the same?
are in the singly linked list. - [ ] The `all()` function returns True if all the items in the list can be
- [ ] The runtime is O(1) because you can index directly to a node in a singly converted to strings. Otherwise, it returns False.
linked list. - [ ] The `all()` function will return all the values in the list.
- [x] The `all()` function returns True if all items in the list evaluate to True.
#### Q28. Given the following three list, how would you create a new list Otherwise, it returns False.
that matches the desired output printed below?
**Explanation** - `all()` returns true if all in the list are True, see example
```python below
fruits = ['Apples', 'Oranges', 'Bananas']
quantities = [5, 3, 4] ```python
prices = [1.50, 2.25, 0.89] test = [True,False,False,False]
if all(test) is True:
#Desired output print('Yeah all are True')
[('Apples', 5, 1.50), else:
('Oranges', 3, 2.25), print('There is an imposter')
('Bananas', 4, 0.89)] >>> 'There is an imposter'
``` ```

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

fruit_tuple_1 = (first[1], quantities[1], price[1]) ```python


output.append(fruit_tuple) >>> dice = Game()
>>> dice.roll()
fruit_tuple_2 = (first[2], quantities[2], price[2]) ```
output.append(fruit_tuple)
-[]B
return output
``` ```python
>>> dice = Game(self)
- [x] B >>> dice.roll(self)
```
```python
i=0 -[]C
output = []
for fruit in fruits: ```python
temp_qty = quantities[i] >>> dice = Game()
temp_price = prices[i] >>> dice.roll(self)
output.append((fruit, temp_qty, temp_price)) ```
i += 1
return output -[]D
```
```python
-[]C >>> dice = Game(self)
>>> dice.roll()
```python ```
groceries = zip(fruits, quantities, prices)
return groceries #### Q31. What is the algorithmic paradigm of quick sort?

>>> [ - [ ] 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. -[]:

#### Q34. What is the definition of abstraction as applied to object- ```python


oriented Python? def sum(a, b):
"""
- [ ] Abstraction means that a different style of code can be used, since a=1
many details are already known to the program behind the scenes. b=2
- [x] Abstraction means the implementation is hidden from the user, and sum(a, b) = 3
only the relevant data or information is shown. """
- [ ] Abstraction means that the data and the functionality of a class are
combined into one entity. return a + b
- [ ] Abstraction means that a class can inherit from more than one parent ```
class.
- [x] :
#### Q35. What does this function print?
```python
```python def sum(a, b):
def print_alpha_nums(abc_list, num_list): """
for char in abc_list: >>> a = 1
for num in num_list: >>> b = 2
print(char, num) >>> sum(a, b)
return 3
"""
print_alpha_nums(['a', 'b', 'c'], [1, 2, 3])
``` return a + b
```
- [x] A
-[]:
```python
a1 ```python
a2 def sum(a, b):
a3 '''
b1 a=1
b2 b=2
b3 sum(a, b) = 3
c1 '''
c2 return a + b
c3 ```
```
**Explanation:** Use `"""` to start and end the docstring and use `>>>` to
-[]B represent the output. If you write this correctly you can also run the
doctest using build-in doctest module
```python
['a', 'b', 'c'], [1, 2, 3] #### Q37. Suppose a Game class inherits from two parent classes:
``` BoardGame and LogicGame. Which statement is true about the methods
of an object instantiated from the Game class?
-[]C
- [ ] When instantiating an object, the object doesn't inherit any of the
```python parent class's methods.
aaa - [ ] When instantiating an object, the object will inherit the methods of
bbb whichever parent class has more methods.
ccc - [ ] When instantiating an object, the programmer must specify which
111 parent class to inherit methods from.
222 - [x] An instance of the Game class will inherit whatever methods the
333 BoardGame and LogicGame classes have.
```
#### Q38. What does calling namedtuple on a collection type return?
-[]D
13
- [ ] a generic object class with iterable parameter fields class test:
- [ ] a generic object class with non-iterable named fields def __init__(self):
- [ ] a tuple subclass with non-iterable parameter fields print('I came here without your permission lol')
- [x] a tuple subclass with iterable named fields pass
t1 = test()
**Example** >>> 'I came here without your permission lol'
```
```python
# namedtuple function accepts the following arguments to generate a #### Q43. What is meant by the phrase "space complexity"?
class
from collections import namedtuple - [ ] `How many microprocessors it would take to run your code in less than
>>> Point = namedtuple('Point',['x','y']) one second`
>>> point = Point(100, 200) - [ ] `How many lines of code are in your code file`
>>> point - [x] `The amount of space taken up in memory as a function of the input
Point(x=100, y=200) size`
- [ ] `How many copies of the code file could fit in 1 GB of memory`
# Which let you use both unpacking and iteration to access
>>> x, y = point #### Q44. What is the correct syntax for creating a variable that is bound
>>> print(f'({x}, {y})') to a dictionary?
(100, 200)
>>> for coordinate in point: - [x] `fruit_info = {'fruit': 'apple', 'count': 2, 'price': 3.5}`
print(coordinate) - [ ] `fruit_info =('fruit': 'apple', 'count': 2,'price': 3.5 ).dict()`
100 - [ ] `fruit_info = ['fruit': 'apple', 'count': 2,'price': 3.5 ].dict()`
200 - [ ] `fruit_info = to_dict('fruit': 'apple', 'count': 2, 'price': 3.5)`
```
#### Q45. What is the proper way to write a list comprehension that
[Reference](https://www.geeksforgeeks.org/namedtuple-in-python/? represents all the keys in this dictionary?
ref=lbp)
`fruits = {'Apples': 5, 'Oranges': 3, 'Bananas': 4}`
#### Q39. What symbol(s) do you use to assess equality between two
elements? - [ ] `fruit_names = [x in fruits.keys() for x]`
- [ ] `fruit_names = for x in fruits.keys() *`
- [ ] `&&` - [x] `fruit_names = [x for x in fruits.keys()]`
- [ ] `=` - [ ] `fruit_names = x for x in fruits.keys()`
- [x] `==`
- [ ] `||` #### Q46. What is the purpose of the `self` keyword when defining or
calling methods on an instance of an object?
#### Q40. Review the code below. What is the correct syntax for changing
the price to 1.5? - [ ] `self` refers to the class that was inherited from to create the object
using `self`.
```python - [ ] There is no real purpose for the `self` method. It's just legacy computer
fruit_info = { science jargon that Python keeps to stay consistent with other
'fruit': 'apple', programming languages.
'count': 2, - [ ] `self` means that no other arguments are required to be passed into
'price': 3.5 the method.
} - [x] `self` refers to the instance whose method was called.
```
**Explanation:** - Try running the example of the Q42 without passing
- [x] `fruit_info ['price'] = 1.5` `self` argument inside the `__init__`, you'll understand the reason. You'll
- [ ] `my_list [3.5] = 1.5` get the error like this `__init__() takes 0 positional arguments but 1 was
- [ ] `1.5 = fruit_info ['price]` given`, this means that something is going inside even if haven't specified,
- [ ] `my_list['price'] == 1.5` which is instance itself.

#### Q41. What value would be returned by this check for equality? #### Q47. What statement about the class methods is true?

`5 != 6` - [ ] A class method is a regular function that belongs to a class, but it must


return None.
- [ ] `yes` - [x] A class method can modify the state of the class, but they can't
- [ ] `False` directly modify the state of an instance that inherits from that class.
- [x] `True` - [ ] A class method is similar to a regular function, but a class method
- [ ] `None` doesn't take any arguments.
- [ ] A class method hold all of the data for a particular class.
**Explanation** - `!=` is equivalent to **not equal to** in python
#### Q48. What does it mean for a function to have linear runtime?
#### Q42. What does a class's `__init__()` method do?
- [ ] You did not use very many advanced computer programming concepts
- [ ] It makes classes aware of each other if more than one class is defined in your code.
in a single code file. - [ ] The difficulty level your code is written at is not that high.
- [ ] It is included to preserve backwards compatibility from Python 3 to - [ ] It will take your program less than half a second to run.
Python 2, but no longer needs to be used in Python 3. - [x] The amount of time it takes the function to complete grows linearly as
- [x] It is a method that acts as a constructor and is called automatically the input size increases.
whenever a new object is created from a class. It sets the initial state of a
new object. #### Q49. What is the proper way to define a function?
- [ ] It initializes any imports you may have included at the top of your file.
- [ ] `def getMaxNum(list_of_nums): # body of function goes here`
**Example:** - [ ] `func get_max_num(list_of_nums): # body of function goes here`
- [ ] `func getMaxNum(list_of_nums): # body of function goes here`
```python - [x] `def get_max_num(list_of_nums): # body of function goes here`
14
- [ ] The top node of the binary search tree would be an arbitrary number.
[explanation for 52 & 53](https://www.python.org/dev/peps/pep-0008/) All the nodes to the left of the top node need to be less than the top
node's number, but they don't need to ordered in any particular way.
#### Q50. According to the PEP 8 coding style guidelines, how should - [ ] The smallest numeric value would go in the top most node. The next
constant values be named in Python? highest number would go in its left child node, the the next highest
number after that would go in its right child node. This pattern would
- [ ] in camel case without using underscores to separate words -- e.g. continue until all numeric values were in their own node.
`maxValue = 255`
- [ ] in lowercase with underscores to separate words -- e.g. `max_value = #### Q55. Why would you use a decorator?
255`
- [x] in all caps with underscores separating words -- e.g. `MAX_VALUE = - [ ] A decorator is similar to a class and should be used if you are doing
255` functional programming instead of object oriented programming.
- [ ] in mixed case without using underscores to separate words -- e.g. - [ ] A decorator is a visual indicator to someone reading your code that a
`MaxValue = 255` portion of your code is critical and should not be changed.
- [x] You use the decorator to alter the functionality of a function without
[Reference](https://realpython.com/python-pep8/) having to modify the functions code.
- [ ] An import statement is preceded by a decorator, python knows to
#### Q51. Describe the functionality of a deque. import the most recent version of whatever package or library is being
imported.
- [ ] A deque adds items to one side and remove items from the other side.
- [ ] A deque adds items to either or both sides, but only removes items #### Q56. When would you use a for loop?
from the top.
- [x] A deque adds items at either or both ends, and remove items at either - [ ] Only in some situations, as loops are used only for certain type of
or both ends. programming.
- [ ] A deque adds items only to the top, but remove from either or both - [x] When you need to check every element in an iterable of known
sides. length.
- [ ] When you want to minimize the use of strings in your code.
**Explanation** - `deque` is used to create block chanin and in that there - [ ] When you want to run code in one file for a function in another file.
is _first in first out_ approch, which means the last element to enter will
be the first to leave. [Reference](https://www.interviewbit.com/python-cheat-sheet/)

#### 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?

- [x] `my_set = {0, 'apple', 3.5}` -[]:


- [ ] `my_set = to_set(0, 'apple', 3.5)`
- [ ] `my_set = (0, 'apple', 3.5).to_set()` ```python
- [ ] `my_set = (0, 'apple', 3.5).set()` def tax(my_float):
'''Calculates the sales tax of a purchase. Takes in a float representing the
#### Q53. What is the correct syntax for defining an `__init__()` method subtotal as an argument and returns a float representing the sales tax.'''
that takes no parameters? pass
```
-[]:
-[]:
```python
class __init__(self): ```python
pass def tx(amt):
``` '''Gets the tax on an amount.'''
```
-[]:
-[]:
```python
def __init__(): ```python
pass def sales_tax(amount):
``` '''Calculates the sales tax of a purchase. Takes in a float representing the
subtotal as an argument and returns a float representing the sales tax.'''
-[]: ```

```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?

#### Q65. Why would you use a virtual environment? -[]:

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

```python if num_people > 10:


def self.get_next_card(): print("There is a lot of people in the pool.")
# method body goes here if num_people > 4:
``` print("There are some people in the pool.")
else:
-[]: print("There is no one in the pool.")
```
```python
def self.get_next_card(self): -[]:
# method body goes here
``` ```python
num_people = 5
#### Q72. What is the correct way to call a function?
if num_people > 10;
- [x] `get_max_num([57, 99, 31, 18])` print("There is a lot of people in the pool.")
- [ ] `call.(get_max_num)` elif num_people > 4;
- [ ] `def get_max_num([57, 99, 31, 18])` print("There are some people in the pool.")
- [ ] `call.get_max_num([57, 99, 31, 18])` else;
print("There is no one in the pool.")
#### Q73. How do you add a comment to existing Python script? ```

- [ ] `-- This is a comment` -[]:


- [x] `# This is a comment`
- [ ] `/* This is a comment */` ```python
- [ ] `// This is a comment` if num_people > 10;
print("There is a lot of people in the pool.")
[Reference](https://realpython.com/python-comments-guide/) if num_people > 4;
print("There are some people in the pool.")
#### Q74. What is the correct syntax for replacing the string apple in the else;
list with the string orange? print("There is no one in the pool.")
```
```python
my_list = ['kiwi', 'apple', 'banana'] #### Q78. How does `defaultdict` work?

- [ ] `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`?

#### Q76. Describe the functionality of a queue? - [ ] `fruit_info['variety'] == 'Red Delicious'`


- [x] `fruit_info['variety'] = 'Red Delicious'`
- [x] A queue adds items to either end and removes items from either end. - [ ] `red_delicious = fruit_info['variety']`
- [ ] A queue adds items to the top and removes items from the top. - [ ] `red_delicious == fruit_info['variety']`
- [ ] A queue adds items to the top, and removes items from anywhere in,
a list. #### Q80. When would you use a `while` loop?
- [ ] A queue adds items to the top and removes items from anywhere in
the queue. - [ ] when you want to minimize the use of strings in your code
- [ ] when you want to run code in one file while code in another file is also
#### Q77. Which choice is the most syntactically correct example of the running
conditional branching? - [x] when you want some code to continue running as long as some
condition is true
- [x] : - [ ] when you need to run two or more chunks of code at once within the
same file
```python
num_people = 5 **Simple Example**
17
```
```python
i=1 -[]:
while i<6:
print('Countdown:',i) ```python
i=i+1 3
``` 3
2
#### Q81. What is the correct syntax for defining an `__init__()` method 2
that sets instance-specific attributes upon creation of a new class 1
instance? 1
```
-[]:
- [x] :
```python
def __init__(self, attr1, attr2): ```python
attr1 = attr1 1
attr2 = attr2 2
``` 3
```
-[]:
#### Q83. In Python, when using sets, you use **\_** to calculate the
```python intersection between two sets and **\_** to calculate the union.
def __init__(attr1, attr2):
attr1 = attr1 - [ ] `Intersect`; `union`
attr2 = attr2 - [ ] `|`; `&`
``` - [x] `&`; `|`
- [ ] `&&`; `||`
- [x] :
#### Q84. What will this code fragment return?
```python
def __init__(self, attr1, attr2): ```python
self.attr1 = attr1 import numpy as np
self.attr2 = attr2 np.ones([1,2,3,4,5])
``` ```

-[]: - [ ] 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 #### Q86. what will this command return?


def count_recursive(n=1):
if n > 3: ```python
return {x for x in range(100) if x%3 == 0}
print(n) ```

count_recursive(n + 1) - [x] a set of all the multiples of 3 less than 100


``` - [ ] a set of all the number from 0 to 100 multiplied by 3
- [ ] a list of all the multiples of 3 less than 100
-[]: - [ ] a set of all the multiples of 3 less than 100 excluding 0

```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?

-[]: - [x] datetime


- [ ] dateday
```python - [ ] daytime
3 - [ ] timedate
2
1 #### Q89. What is the correct syntax for defining a class called Game?
18
- [ ] `def Game(): pass` #### Q94. Which command will create a list from 10 down to 1? Example:
- [ ] `def Game: pass`
- [x] `class Game: pass` `[10,9,8,7,6,5,4,3,2,1]`
- [ ] `class Game(): pass`
- [ ] `reversed(list(range(1,11)))`
[reference here](https://docs.python.org/3/tutorial/classes.html) - [ ] `list(reversed(range(1,10)))`
- [ ] `list(range(10,1,-1))`
#### Q90. What is the correct syntax for calling an instance method on a - [x] `list(reversed(range(1,11)))`
class named Game?
[Reference](https://www.w3schools.com/python/python_tuples.asp)
- [ ] `my_game = Game(self) self.my_game.roll_dice()`
- [ ] `my_game = Game() self.my_game.roll_dice()` #### Q95. Which fragment of code will print exactly the same output as
- [x] `my_game = Game() my_game.roll_dice()` this fragment?
- [ ] `my_game = Game(self) my_game.roll_dice(self)`
```python
#### Q91. What is the output of this code? (NumPy has been imported as import math
np.)? print(math.pow(2,10)) # prints 2 elevated to the 10th power
```
```python
a = np.array([1,2,3,4]) -[]:
print(a[[False, True, False, False]])
``` ```python
print(2^10)
- [ ] `{0,2}` ```
- [x] `[2]`
- [ ] `{2}` - [x] :
- [ ] `[0,2,0,0]`
```python
#### Q92. Suppose you have a string variable defined as print(2**10)
y="stuff;thing;junk;". What would be the output from this code? ```

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

- [ ] `my_keys = fruit_info.to_keys()` ```python


- [ ] `my_keys = fruit_info.all_keys()` c = a[0] * b[0], a[1] * b[1], a[2] * b[2]
- [ ] `my_keys = fruit_info.keys`
- [x] `my_keys = fruit_info.keys()` d = [ a[0] * b[0], a[1] * b[1], a[2] * b[2] ]
```
#### Q111. What is wrong with this function definition?
-[]C
```python
def be_friendly(greet = "How are you!", name): ```python
pass c = [ a[0] * b[0], a[1] * b[1], a[2] * b[2] ]
```
d = sum(a) + sum(b)
- [ ] `name` is a reserved word. ```
- [ ] Underscores are not allowed in function names.
- [x] A non-default argument follows a default argument. - [x] D
- [ ] There is nothing wrong with this function definition.
```python
#### Q112. Given that NumPy is imported as `np`, which choice will return c = [ a[0] * b[0], a[1] * b[1], a[2] * b[2] ]
`True`?
d = sum(c)
- [x] : ```

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

```python **Explanation:** Understanding this answer requires knowledge of linear


a = np.empty([3,4]) algebra. Some systems of equations can be solved by the method of
b = np.empty([3,4]) _diagonalization_, which involves finding the **eigenvectors and
np.array_equal(a,b) eigenvalues** of the system's matrix and multiplying related matrices.
```
#### Q116. What is the correct syntax for creating a variable that is bound
-[]: to a list?

```python - [ ] `my_list = (2, 'apple', 3.5)`


a = np.zeros([3,4]) - [x] `my_list = [2, 'apple', 3.5]`
b = np.zeros([4,3]) - [ ] `my_list = [2, 'apple', 3.5].to_list()`
np.array_equal(a,b) - [ ] `my_list = to_list(2, 'apple', 3.5)`
```
[Reference](https://www.tutorialspoint.com/python/python_lists.htm)
-[]:
#### Q117. This code provides the **\_** of the list of numbers.
```python
a = np.array([1, np.nan]) ```python
np.array_equal(a,a) num_list = [21, 13, 19, 3, 11, 5, 18]
``` num_list.sort()
num_list[len(num_list) // 2]
#### Q113. How do you add a comment to existing Python script? ```

- [ ] `// This is a comment` - [ ] mode


- [x] `# This is a comment` - [ ] average
- [ ] `-- This is a comment` - [ ] mean
- [ ] `/* This is a comment *\` - [x] median

#### 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?

-[]A - [ ] Arrays and DataFrames


- [ ] Series and Matrixes
```python - [ ] Matrixes and DataFrames
c = [ a[1] * b[1], a[2] * b[2], a[3] * b[3] ] - [x] Series and DataFrames
21
[Reference](https://pandas.pydata.org/docs/user_guide/dsintro.html) #### Q123. Using Pandas, we load a data set from Kaggle, as structured in
the image below. Which command will return the total number of
#### Q119. Suppose you have a variable named `vector` of type np.array survivors?
with 10,000 elements. How can you turn `vector` into a variable named
`matrix` with dimensions 100x100? ![Q129](images/Q129.png?raw=png)

- [ ] `matrix = (vector.shape = (100,100))` - [x] `sum(titanic['Survived'])`


- [ ] `matrix = vector.to_matrix(100,100)` - [ ] `[x for x in titanic['Survived'] if x == 1]`
- [ ] `matrix = matrix(vector,100,100)` - [ ] `len(titanic["Survived"])`
- [x] `matrix = vector.reshape(100, 100)` - [ ] `sum(titanic['Survived']==0)`

[Reference](https://www.w3schools.com/python/numpy/ **Explanation:** The `titanic['Survived']` returns a `pandas.Series` object,


numpy_array_reshape.asp) which contains the `Survived` column of the `DataFrame`.
Adding the values of this column (i.e. `sum(titanic['Survived'])`) returns the
#### Q120. Which choice is an immutable data type? total number of survivors since a survivor is represented by a 1 and a loss
by 0.
- [ ] dictionnary
- [ ] list #### Q124. How would you create a list of tuples matching these lists of
- [ ] set characters and actors?
- [x] string
```python
[Reference](https://www.tutorialspoint.com/python_text_processing/ characters = ["Iron Man", "Spider Man", "Captain America"]
python_string_immutability.htm) actors = ["Downey", "Holland", "Evans"]

#### 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 = {}

-[]: for x in range(1, len(characters)):


d[x] = actors[x]
```python ```
Hello, I am from Spain
Hello, I am from - [ ] `{x:y for x in characters for y in actors}`
Hello, I am from
``` #### Q125. What will this statement return?

-[]: ```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
``` ![Q132](images/Q132.png?raw=png)

-[]: - [ ] `def jaccard(a, b): return len (a | b) / len (a & b)`


- [x] `def jaccard(a, b): return len (a & b) / len (a | b)`
```python - [ ] `def jaccard(a, b): return len (a && b) / len (a || b)`
Hello, I am from Spain - [ ] `def jaccard(a, b): return a.intersection(b) / a.union(b)`
Hello, I am from France
Hello, I am from France [Reference](https://docs.python.org/3/tutorial/datastructures.html?
``` highlight=set#sets.)

#### 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](images/Q138.png?raw=png)

- [ ] def*init*(self): pass - [ ] `random.uniform(0,50);plt.hist`


- [ ] class*init*(self): pass - [x] `random.gauss(50,20);plt.hist`
- [ ] class*init*(): pass - [ ] `random();plt.scatter`
- [x] def*init*(): pass - [ ] `random.triangular(0,50);plt.bar`

() -empty parameter [Reference](https://www.geeksforgeeks.org/random-gauss-function-in-


self -refers to all instances within a class python/)
_init_ -a reserved method, aka a constructor
_init_() -always executed when the class is being initiated #### Q139. In this code fragment, what will be the values of a and b ?

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

- [ ] `using math.sin` a = np.arange(100)


- [ ] `import math.sin` b = a[50:60:2]
- [x] `from math import sin` ```
- [ ] `import sin from math`
- [x] a: all integers from 0 to 99 (inclusive) b: all even integers from 50 to
[Reference](https://www.datacamp.com/tutorial/modules-in- 58 (inclusive)
python#more-on-import-statements) - [ ] a: all integers from 0 to 100 (inclusive) b: all even integers from 50 to
60 (inclusive)
**Explanation:** The `from..import` statement allows you to import - [ ] a: all integers from 0 to 99 (inclusive) b: all even integers from 50 to 60
specific functions/variables from a module instead of importing (inclusive)
everything. - [ ] a: all integers from 0 to 99 (inclusive) b: all odd integers from 49 to 59
(inclusive)
#### Q133. What do you get if you apply numpy.sum() to a list that
contains only Boolean values? #### Q140. When using NumPy in Python, how do you check the
dimensionality (number and length of dimensions) of an object called
- [ ] `0` my_object?
- [x] `the count of all True values`
- [ ] `a type error` - [ ] `my_object.get_shape()`
- [ ] `None` - [x] `my_object.shape`
- [ ] `my_object.dim()`
#### Q134. What will this code print? - [ ] `len(my_object)`

```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 _**?

- [ ] True - [ ] `len(mylist); len(mylist)`


- [x] foo - [x] `1; len(mylist)`
- [ ] You will get an error message because constant integer values are not - [ ] `2; len(mylist)`
classes. - [ ] `0; len(mylist)`
- [ ] bar
**Explanation:** Can use a break statement and the value being searched
#### Q135. If you do not explicitly return a value from a function, what can be the first element of the list, given that it is non-empty.
happens?
#### Q142. If a function does not have a return statement, what does it
- [ ] If the return keyword is absent, the function will return True. really return?
- [ ] The function will enter an infinite loop because it will not know when
to stop executing its code. -[]0
23
- [ ] True king.introduce()
- [x] None
- [ ] False ```

#### Q143. What is a common use of python's sys library? - [x] :

- [x] to capture command-line arguments given at a file's runtime ```python


- [ ] to take a snapshot of all the packages and libraries in your virtual class Father():
environment name = 'Robert'
- [ ] to connect various systems, such as connecting a web front end, an
API service, a database, and a mobile app
- [ ] to scan the health of your Python ecosystem while inside a virtual class Person(Father):
environment def __init__(self, name):
self.fathername = self.name
[Reference](https://docs.python.org/3/library/sys.html) self.name = name

#### 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?

```python king = Person("Joffrey")


import numpy as np king.introduce()

def can_matrices_be_multiplied (matrix1, matrix2): ```


rowsMat1, columnsMat1 = matrix1.shape
rowsMat2, columnsMat2 = matrix2.shape -[]:

if _____ == ______ : ```python


print('The matrices can be multipled!') class Father():
return True name = 'Robert'
else:
return False
``` class Person(Father):
def __init__(self, name):
- [ ] columnsMat1; rowsMat1; self.name = name
- [x] columnsMat1; rowsMat2;
- [ ] columnsMat1; columnsMat2; def introduce(self):
- [ ] columnsMat2; rowsMat1; print("My name is", self.name, "son of", super.name)

#### Q145. What is the output of this comprehension? king = Person("Joffrey")


king.introduce()
`[(x, x+1) for x in range(1,5)] ` ```

- [ ] [(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 #### Q152. What is the maximum length of a Python identifier?


['beetle', 'bear', 'bat']
[] - [ ] 32
``` - [ ] 16
- [ ] 128
-[]B - [x] No fixed length is specified

```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:

-[]D - [ ] Formatted string expressions


- [ ] Functional strings
```python - [ ] Modulo formatted strings
['bat', 'bear', 'beetle'] - [x] Formatted string literals
[]
``` #### Q155. How many CPUs (or cores) will the Python threading library
take advantage of simultaneously?
**Explanation:** Dictionaries usually result in an exception when using
the square bracket syntax. Defaultdict here returns a default value - [x] One
dedicated by the first parameter so instead of throwing an exception, they - [ ] All of the available CPUs
return the default. Note that this needs to be imported as follows: `from - [ ] Two
collections import defaultdict` - [ ] Three

[Reference](https://www.geeksforgeeks.org/defaultdict-in-python/) **Explanation**: Python threading is restricted to a single CPU at one


time. The multiprocessing library will allow you to run code on different
#### Q149. What will this line of code return? (Assume n is already processors.
defined as any positive integer value.)
#### Q156. What will be the value of y in this code?
```python
[x*2 for x in range(1,n)] ```python
``` x=5
y = 1 + (20 if x < 5 else 30)
- [x] a list with all the even numbers less than 2\*n ```
- [ ] a dictionary with all the even numbers less than 2\*n
- [ ] a list with all the odd numbers less than 2\*n - [ ] False
- [ ] a list with all the even numbers less than or equal to 2\*n - [ ] 21
-[]2
[Reference](https://www.w3schools.com/python/ref_func_range.asp) - [x] 31

#### 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.

if x > 10: ```python


if x > 15: x=5
print('A') # This is the same statement expanded to multiple lines
else: y=1
print('B') if (x < 5):
else: y += 20
print('C') else:
y += 30
``` ```

-[]C #### Q157.The process of pickling in Python includes?


-[]AB
-[]B - [x] conversion of a Python object hierarchy into byte stream
- [x] A - [ ] conversion of a datatable into a list
- [ ] conversion of a byte stream into Python object hierarchy
#### Q151. Suppose you have a variable named vector of type np.array - [ ] conversion of a list into a datatable
with 10.000 elements. How can you turn vector into a variable named
matrix with dimensions 100x100? **Explanation:** Pickling is the process of sterilizing a Python object, that
is, conversion of a byte stream into Python object hierarchy. The reverse
- [ ] matrix = matrix(vector,100,100) of this process is known as unpickling.
- [ ] matrix = vector.to_matrix(100,100)
- [ ] matrix = (vector.shape = (100,100)) #### Q158. What is the output of the following program ?
25
``` - [ ] 1 2 3 4 5 Done!
print("codescracker".endswith("er")) - [ ] 0 1 2 3 4 5 Done!
``` - [x] 0 1 2 3 4 Done!
- [ ] You will get a syntax error.
- [x] True
-[]1 #### Q166. Which comparison of lists and tuples in Python is correct?
-[]2
- [ ] False - [ ] Use lists instead of tuples when you have a collection of related but
dissimilar objects.
#### Q159. Is list mutable in python ? - [ ] Use tuples instead of lists when you have a common collection of
similar objects.
- [x] True - [x] Use tuples instead of lists for functions that need to return multiple
- [ ] False values.
- [ ] Use lists instead of tuples when the position of elements is important.
#### Q160. What is the output of the following program ?
[Reference](https://www.scaler.com/topics/python/tuples-in-python/)
print("programming".center())
#### Q167. Consider the following code snippet that uses decorators to
- [ ] cr calculate the execution time of execution_fn function:
- [ ] programming
- [x] Error says TypeError: center expected at least 1 argument, got 0 ```python
- [ ] None of the Above import functools
import time
#### Q161. Who created the Python programming language?
def timer(MISSING_ARG_1):
- [ ] Tim Berners-Lee @functools.wraps(func)
- [ ] Ada Lovelace def wrapper(*args, **kwargs):
- [x] Guido van Rossum start_time = time.perf_counter()
- [ ] Alan Turing rval = func(*args, **kwargs)
end_time = time.perf_counter()
#### Q162. Which collection is ordered, changeable, and allows duplicate duration = end_time - start_time
members? print(f"Executed in {duration:.4f} seconds")
return MISSING_ARG_2
- [ ] SET return MISSING_ARG_3
- [ ] TUPLE
- [ ] DICTIONARY @timer
- [x] LIST def execution_fn():
for i in range(3):
#### Q163. What will be printed in the console if you run this code? time.sleep(1)

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

- [x] 33 MISSING_ARG_2 = rval


- [ ] 63
- [ ] 0xA + 0xB + 0xC MISSING_ARG_3 = wrapper
- [ ] None ```

**Explanation:** A, B and C are hexadecimal integers with values 10, 11 -[]:


and 12 respectively, so the sum
of A, B and C is 33. ```
MISSING_ARG_1 is empty
#### Q165. What will this code output to the screen?
MISSING_ARG_2 = rval
```python
for i in range(5): MISSING_ARG_3 = wrapper
print(i) ```
else:
print("Done!") -[]:
```
26
``` method could you call to see which method will get priority when
MISSING_ARG_1 is empty invoked?

MISSING_ARG_2 = rval - [x] `MyClass.__mro__`


- [ ] `MyClass.hierarchy()`
MISSING_ARG_3 = func - [ ] `callable(MyClass)`
``` - [ ] `dir(MyClass)`

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

```python The command employees['alice']['salary'] = employees['charlie']['salary']


a = np.array([[1, 2], [3, 4], [5, 6]]) assigns the value of the 'salary' key in the dictionary of the employee
c = a[(a > 3) & (a < 11)] 'charlie' to the 'salary' key in the dictionary of the employee 'alice'.
print(c) It is the same thing as:
```
```python
- [ ] `[[3, 4], [5, 6]]` employees = {
- [ ] `[False, False, False, True, True, True]` 'alice': {'position': 'Lead Developer', 'salary': 1000},
- [ ] `[[0,0], [3, 4], [5, 6]]` 'bob': {'position': 'Lead Artist', 'salary': 2000},
- [x] `[4 5 6]` 'charlie': {'position': 'cfo', 'salary': 3000}
}
#### Q173. What is the correct syntax for replacing the string `apple` in # or:
the list with the string `orange`? employees = {'alice': {'position': 'Lead Developer', 'salary': 1000},
'bob': {'position': 'Lead Artist', 'salary': 2000},
```python 'charlie': {'position': 'cfo', 'salary': 3000}}
my_list = [2, 'apple', 3.5] ```
```
#### Q177. You are given a piece of code. Assume m and n are already
- [ ] `orange = my_list[1]` defined as some positive integer value. When it completes, how many
- [x] `my_list[1] = 'orange'` tuples will my list contain?
- [ ] `my_list['orange'] = 1`
- [ ] `my_list[1] == orange` ```python
mylist = []
#### Q174. Assume m, n and p are positive integers. In the following
comprehension, how many times will the function `randint` be called? for i in range(m):
for j in range(n):
```python mylist.append((i,j))
[ [ [ randint(1,100) for i in range(m) ] for j in range(n) ] for k in range(p) ] ```
```
-[]m
- [x] m _ n _ p -[]m+n
- [ ] the greater value of (m,n,p) -[]n
- [ ] 1 million - [x] m \* n
-[]m+n+p
**Explanation:** This code will run for m x n times, if you run this code, it
#### Q175. Suppose you have a class named MyClass which has multiple will create m x n tuples. <br/> The first loop runs for m times and the inner
inheritance and methods with the same name in its ancestors. Which class loop will run for n times. While the single iteration of first loop will only be
27
completed when all of the n iterations of inner loop are completed. This is <value>Value1</value>
the same process for 2nd, 3rd, ... mth iterations for outer loop. Overall, <value>Value2</value>
both loops will run m x n times </values>
</entry>
#### Q178. What will this comprehension provide you? <entry>
<name>Set2</name>
```python <values>
{x : [y for y in range (1, x) if x % y == 0] for x in range (2, 100)} <value>Value3</value>
``` <value>Value4</value>
</values>
- [x] a dictionary whose keys are the numbers from 2 to 99 (inclusive), and </entry>
their respective values are their factors <!-- Add more entries as needed -->
- [ ] a dictionary whose keys are the numbers from 2 to 99 (inclusive), and </data>
their respective values are a list from 1 to the key value itself (inclusive)
- [ ] a dictionary whose keys are the numbers from 2 to 99 (inclusive), and
their respective values are the even numbers from 1 to the key value itself You can create a Python script to search for the values associated with a
(inclusive) given name as follows:
- [ ] a dictionary whose keys are the numbers from 2 to 99 (inclusive), and
their respective values are the odd numbers from 1 to the key value itself import xml.etree.ElementTree as ET
(inclusive)
# Parse the XML file
#### Q179. What operator do you use to assess equality between two tree = ET.parse('data.xml')
elements? root = tree.getroot()

-[]= # Function to search for values based on a name


- [ ] && def find_values_by_name(name):
- [ ] || for entry in root.findall('entry'):
- [x] == entry_name = entry.find('name').text
if entry_name == name:
values = [value.text for value in entry.find('values')]
2.5. CHAT GPT return values
2.5.1. return None
I have a xml file with many set of values and a name for each set. I
want I python script which can serch the corresponding set of values # Test the function with a specific name
for a given name. Show me an example search_name = 'Set2'
result = find_values_by_name(search_name)
To search for a corresponding set of values in an XML file for a given name,
you can use the `xml.etree.ElementTree` module in Python. First, you need if result is not None:
to parse the XML file, and then you can search for the desired set of values print(f"Values for {search_name}: {', '.join(result)}")
based on the name. Here's an example of how to do this: else:
print(f"Name '{search_name}' not found.")
Suppose you have an XML file named `data.xml` with the following
content:
In this script, the `find_values_by_name` function iterates through the
<data> `<entry>` elements in the XML file, checks the `<name>` element of each
<entry> entry, and returns the associated values if the name matches the input.
<name>Set1</name> You can customize this script and XML structure to match your specific
<values> data.

28

You might also like