honPyt Flashcards

(166 cards)

1
Q

While using Python in interactive mode, which variable is the default prompt for continuation lines?

A

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

While using Python in interactive mode, which variable holds the value of the last printed expression?

A

_ (underscore)

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

With the variable assignment name=”Python”, what will be the output of print(name[-1])?

A

“n”

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

What would be the output of this code?

def welcome(name):
    return "Welcome " + name, "Good Bye " + name

wish = welcome(“Joe”)
print(wish)

(Brainscape doesn’t seem to allow indentation, so just pretend this is all indented properly)

A

(‘Welcome Joe’, ‘Good Bye Joe’)

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

What would be the output of this code?

A = 15
B = 10
C = A/B
D = A//B
E = A%B
print(C)
print(D)
print(E)
A

1.5
1
5

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

What does the “//” operator do?

A

Floor division (or integer division), a normal division operation except that it returns the largest possible integer.

(this behaves differently when negative numbers are involved)

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

What would be the output of this code?

Elements=["ether", "air", "fire", "water"]
print(Elements[0])
print(Elements[3])
print(Elements[2])
Elements[2] = "earth"
print(Elements[2])
A

ether
water
fire
earth

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

What would be the output of this code?

data = (x*10 for x in range(3))
for i in data:
    print(i)
for j in data:
    print(j)

(Brainscape doesn’t seem to allow indentation, so just pretend this is all indented properly)

A

0
10
20

(this only returns the first loop, as generator data can only be used once)

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

What would be the output of this code?

names = ['a', 'b', 'c']
names_copy = names
names_copy[2] = 'h'
print(names)
print(names_copy)
A

[‘a’, ‘b’, ‘h’]
[‘a’, ‘b’, ‘h’]

In Python, Assignment statements do not copy objects, they create bindings between a target and an object

It only creates a new variable that shares the reference of the original object

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

What would be the output of this code?

x = 3 + 2j
y = 3 - 2j
z = x + y
print(z)

A

(6+0j)

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

What would be the output of this code?

for i in range(3):
print(i)
else:
print(“Done!”)

(Brainscape doesn’t seem to allow indentation, so just pretend this is all indented properly)

A

0
1
2
Done!

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

What is the slicing operator in Python?

A

:

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

What does trunc() do?

A

trunc() rounds down positive floats, and rounds up negative floats

math. trunc(3.5) # 3
math. trunc(-3.5) # -3

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

Can you use remove() to delete an element from an array by giving it an index number?

A

No

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

What keyword can be used to remove an item from a list based on its index?

A

del

numbers = [50, 60, 70, 80]
del numbers[1] # numbers = [50, 70, 80]

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

How would you use pop() to remove the first element of an array?

A

pop(0)

numbers = [50, 60, 70, 80]
numbers.pop(0) # [60, 70, 80]

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

What would be the output of this code?

a, b, c, d = 1, ‘cat’, 6, 9
print(c)

A

6

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

What would be the output of this code?

a, b, c, d = 1
print(c)

A

TypeError: cannot unpack non-iterable int object

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

What is the lambda keyword used for?

A

It is used for creating simple anonymous functions

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

What keyword can be used to force a particular exception to occur?

A

raise

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

Which module will process command line arguments for a Python script?

A

os

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

What is the syntax of a lambda function on Python?

A

lambda arguments: expression

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

How would you make a deep copy of an array?

A

Use copy()

arr2 = arr1.copy()

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

Using filter() how would you use lambda to select all numbers over 5 from array my_list?

A

filter(lambda x: x > 5, my_list)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Can lambda only be used for numeric expressions?
Yes
26
Which if the following statements will not print all the elements of the list below? letters=["d","e","a","g","b"] print(letters[:]) print(letters[0:]) print(letters[:-3]) print(letters[:10])
print(letters[:-3])
27
What would be the output of the code below? ``` >>> a = "Welcome" >>> b = "Welcome" >>> c = "Good-Bye" >>> d = "Good-Bye" >>> a is b >>> c is d ```
True False "Welcome" and "Welcome" turn out to be the same because they are constants, less than 20 characters long or not subject to constant folding (in this case both!), and contain only ASCII letters, digits and underscores
28
Which function will return DirEntry objects instead of strings while trying to list the contents of the directory?
os.scandir()
29
What is an abstract class?
An abstract class exists only so that other "concrete" classes can inherit from the abstract class
30
What happens when you use any() on a list?
The any() function returns True if any item in the list evaluates to True. Otherwise, it returns False
31
What data structure does a binary tree degenerate to if it isn't balanced properly?
linked list
32
What are static methods?
Static methods serve mostly as utility methods or helper methods, since they can't access or modify a class's state
33
What are attributes?
Attributes are a way to hold data, or describe a state for a class or an instance of a class
34
What is the term to describe this code? count, fruit, price = (2, 'apple', 3.5)
tuple unpacking
35
What built-in list method would you use to remove items from a list?
pop()
36
What is one of the most common use of Python's sys library?
to capture command-line arguments given at a file's runtime
37
What is the runtime of accessing a value in a dictionary by using its key?
O(1), also called constant time
38
What is the correct syntax for defining a class called Game?
class Game:
39
What is the correct way to write a doctest? ``` A def sum(a, b): """ sum(4, 3) 7 sum(-4, 5) 1 """ return a + b ``` ``` B def sum(a, b): """ >>> sum(4, 3) 7 >>> sum(-4, 5) 1 """ return a + b ``` ``` C def sum(a, b): """ # >>> sum(4, 3) # 7 # >>> sum(-4, 5) # 1 """ return a + b ``` ``` D def sum(a, b): ### >>> sum(4, 3) 7 >>> sum(-4, 5) 1 ### return a + b ```
``` def sum(a, b): """ >>> sum(4, 3) 7 >>> sum(-4, 5) 1 """ return a + b ```
40
What built-in Python data type is commonly used to represent a stack?
list | you can only build a stack from scratch
41
What would this expression return? ``` college_years = ['Freshman', 'Sophomore', 'Junior', 'Senior'] return list(enumerate(college_years, 2019)) ```
[(2019, 'Freshman'), (2020, 'Sophomore'), (2021, 'Junior'), (2022, 'Senior')]
42
How does defaultdict work?
If you try to access a key in a dictionary that doesn't exist, defaultdict will create a new key for you instead of throwing a KeyError
43
What is the correct syntax for defining a class called "Game", if it inherits from a parent class called "LogicGame"?
class Game(LogicGame):
44
What is the purpose of the "self" keyword when defining or calling instance methods?
self refers to the instance whose method was called
45
Can you assign a name to each of the namedtuple members and refer to them that way, similarly to how you would access keys in dictionary?
Yes
46
What is an instance method?
Instance methods can modify the state of an instance or the state of its parent class
47
Which choice is the most syntactically correct example of the conditional branching?
num_people = 5 if num_people > 10: print("There is a lot of people in the pool.") elif num_people > 4: print("There are some people in the pool.") elif num_people > 0: print("There are a few people in the pool.") else: print("There is no one in the pool.")
48
Is it true that encapsulation only allows data to be changed by methods?
No
49
What is the purpose of an if/else statement?
It executes one chunk of code if a condition is true, but a different chunk of code if the condition is false
50
What built-in Python data type is commonly used to represent a queue?
list
51
What is the correct syntax for instantiating a new object of the type Game?
x = Game()
52
What does the built-in map() function do?
It applies a function to each item in an iterable and returns the value of that function
53
If there is no return keyword in a function, what happens?
If the return keyword is absent, the function will return None
54
What is the purpose of the pass statement in Python?
It is a null operation used mainly as a placeholder in functions, classes, etc. If you have a loop or a function that is not implemented yet, but we want to implement it in the future, it cannot have an empty body. The interpreter would give an error. So, we use the pass statement to construct a body that does nothing
55
What is the term used to describe items that may be passed into a function?
arguments
56
Which collection type is used to associate values with unique keys?
dictionary
57
When does a for loop stop iterating?
when it has assessed each item in the iterable it is working on, or a break keyword is encountered
58
What is the runtime complexity of searching for a specific node within a singly linked list?
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
59
Given the following three lists, how would you create a new list that matches the desired output printed below? ``` fruits = ['Apples', 'Oranges', 'Bananas'] quantities = [5, 3, 4] prices = [1.50, 2.25, 0.89] ``` Desired output [('Apples', 5, 1.50), ('Oranges', 3, 2.25), ('Bananas', 4, 0.89)]
``` i = 0 output = [] for fruit in fruits: temp_qty = quantities[i] temp_price = prices[i] output.append((fruit, temp_qty, temp_price)) i += 1 return output ``` (Brainscape doesn't seem to allow indentation, so just pretend this is all indented properly)
60
What happens when you use the built-in function all() on a list?
The all() function returns True if all items in the list evaluate to True. Otherwise, it returns False
61
What is the correct syntax for calling an instance method on a class named Game?
>>> dice = Game() | >>> dice.roll()
62
What is the algorithmic paradigm of quick sort? backtracking dynamic programming decrease and conquer divide and conquer
divide and conquer
63
What is runtime complexity of the list's built-in .append() method?
O(1), also called constant time
64
What is key difference between a set and a list?
A set is an unordered collection items with no duplicates A list is an ordered collection of items, that may include duplicates
65
What is the definition of abstraction as applied to object-oriented Python?
Abstraction means the implementation is hidden from the user, and only the relevant data or information is shown
66
What does this function print? ``` def my_func(abc_list, num_list): for char in abc_list: for num in num_list: print(char, num) return ``` my_func(['a', 'b', 'c'], [1, 2, 3])
``` a 1 a 2 a 3 b 1 b 2 b 3 c 1 c 2 c 3 ```
67
What is the correct syntax for calling an instance method on a class named DiceGame?
my_var = DiceGame() | my_var.roll_dice()
68
Correct representation of doctest for function in Python
``` def sum(a, b): """ >>> a = 1 >>> b = 2 >>> sum(a, b) 3 """ ``` return a + b
69
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?
An instance of the Game class will inherit whatever methods the BoardGame and LogicGame classes have
70
What does calling namedtuple on a collection type return?
a tuple subclass with iterable named fields
71
What symbol(s) do you use to assess equality between two elements?
==
72
``` fruit_info = { 'fruit': 'apple', 'count': 2, 'price': 3.5 } ``` Using new code, how would you change the price to 1.5?
fruit_info ['price'] = 1.5
73
What value would be returned by this check for equality? 5 != 6
True
74
What does a class's init() method do?
The __init__ method is a constructor method that is called automatically whenever a new object is created from a class. It sets the initial state of a new object
75
What is meant by the phrase "space complexity"?
The amount of space taken up in memory as a function of the input size
76
What is the correct syntax for creating a variable that is bound to a dictionary?
fruit_info = {'fruit': 'apple', 'count': 2, 'price': 3.5}
77
What is the proper way to write a list comprehension that represents all the keys in this dictionary? fruits = {'Apples': 5, 'Oranges': 3, 'Bananas': 4}
fruit_names = [x for x in fruits.keys()]
78
What is the purpose of the self keyword when defining or calling methods on an instance of an object?
self refers to the instance whose method was called
79
What statement about class methods is true? A class method is a regular function that belongs to a class, but it must return None. A class method can modify the state of the class, but they can't directly modify the state of an instance that inherits from that class. A class method is similar to a regular function, but a class method doesn't take any arguments. A class method holds all of the data for a particular class.
A class method can modify the state of the class, but they can't directly modify the state of an instance that inherits from that class
80
What does it mean for a function to have a linear runtime?
The amount of time it takes the function to complete grows linearly as the input size increases
81
What is the proper way to define a function? def getMaxNum(list_of_nums): func get_max_num(list_of_nums): func getMaxNum(list_of_nums): def get_max_num(list_of_nums)
def get_max_num(list_of_nums):
82
According to the PEP 8 coding style guidelines, how should constant values be named in Python?
In all caps with underscores separating words MAX_VALUE = 255
83
Describe the functionality of a deque.
A deque adds items at either or both ends, and remove items at either or both ends
84
What is the correct syntax for creating a variable that is bound to a set?
myset = {0, 'apple', 3.5}
85
What is the correct syntax for defining an __init__() method that takes no parameters and returns nothing?
``` def __init__(self): pass ```
86
Can a class method modify the state of the class, or modify the state of an instance that inherits from that class?
A class method can modify the state of the class, but it cannot directly modify the state of an instance that inherits from that class
87
Which of the following is TRUE about how numeric data would be organised in a binary Search tree?
For any given Node in a binary Search Tree, the child node to the left is less than the value of the given node and the child node to its right is greater than the given node
88
Why would you use a decorator?
You use a decorator to alter the functionality of a function, without having to modify the functions code
89
When would you use a for loop?
When you need to check every element in an iterable of known length
90
What would happen if you did not alter the state of the element that an algorithm is operating on recursively?
You would get a RuntimeError: maximum recursion depth exceeded
91
What is the runtime complexity of searching for an item in a binary search tree?
The runtime for searching in a binary search tree is generally O(h), where h is the height of the tree
92
Why would you use a mixin?
If you have many classes that all need to have the same functionality, you'd use a mixin to define that functionality
93
What is the runtime complexity of adding an item to a stack and removing an item from a stack?
O(1) time
94
Where does a stack add items to, and where does it remove items from?
a stacks adds items to the top and removes items from the top FIFO
95
What is a base case in a recursive function?
A base case is the condition that allows the algorithm to stop recursing. It is usually a problem that is small enough to solve directly
96
Why is it considered good practice to open a file from within a Python script by using the with keyword?
When you open a file using the with keyword in Python, Python will make sure the file gets closed, even if an exception or error is thrown
97
Why would you use a virtual environment?
Virtual environments create a "bubble" around your project so that any libraries or packages you install within it don't affect your entire machine
98
What is the correct way to run all the doctests in a given file from the command line?
python3 filename . py
99
What is a lambda function?
a small, anonymous function that can take any number of arguments, but has only 1 expression to evaluate
100
What is the primary difference between lists and tuples?
Lists are mutable, meaning you can change the data that is inside them at any time. Tuples are immutable, meaning you cannot change the data that is inside them once you have created the tuple
101
How are static methods used?
Static methods serve mostly as utility or helper methods, since they cannot access or modify a class's state
102
What does a generator return?
An iterable object, that does not exist in memory
103
What is the difference between class attributes and instance attributes?
Class attributes are shared by all instances of the class. Instance attributes may be unique to just that instance
104
What is the correct syntax of creating an instance method?
def get_next_card(self):
105
What is a key difference between a set and a list?
A set is an unordered collection of unique items. A list is an ordered collection of non-unique items
106
What is the correct way to call a function?
get_max_num([57, 99, 31, 18])
107
How is a single line comment created?
#
108
What is the correct syntax for replacing the string "apple" in the my_list with the string "orange"?
my_list[1] = 'orange'
109
What will happen if you use a while loop and forget to include logic that eventually causes the while loop to stop?
Your code will get stuck in an infinite loop
110
Describe the functionality of a deque.
A deque adds items to either end, and removes items from either end
111
Which choice is the most syntactically correct example of the conditional branching?
num_people = 5 if num_people > 10: print("There is a lot of people in the pool.") elif num_people > 4: print("There are some people in the pool.") else: print("There is no one in the pool.")
112
How does defaultdict work?
If you try to read from a defaultdict with a nonexistent key, a new default key-value pair will be created for you instead of throwing a KeyError
113
Which math function can find whether 2 given numbers are approximately equal or not based on a given tolerance?
math.isclose() (default tolerance is is 1e-09, or 1 / 1,000,000,000)
114
Why would you use deque() in Python?
deques are built to be super fast when adding or removing items from both ends. Lists are quite fast, in python terms, when doing stuff on the end of a list but has to do all sorts of computation to operate on the start of a list
115
What is constant folding?
When you have an expression like 1 + 1, the compiler evaluates that and puts in the constant 2, instead of leaving it to the interpreter
116
What are some problems with comparing strings using "is"?
"Welcome" and "Welcome" turn out to be the same because they are constants, less than 20 characters long or not subject to constant folding (in this case both!), and contain only ASCII letters, digits and underscores "Good-Bye" and "Good-Bye" do NOT meet these conditions because they contain a "-"
117
In VS Code, what is the shortcut to open the command palette? What is the command to run Python's REPL?
Ctrl+Shift+P Python: Start REPL
118
What would you use to chop a string into blocks by a space?
split(' ')
119
How can you print out a variable's name and it's value in the most concise way possible?
print(f"{my_var = }") | remember "f quote curly"
120
Is it true that no import is needed to use namedtuples?
No from collections import namedtuple
121
Can each member of a namedtuple object be indexed to directly, just like in a regular tuple?
Yes
122
Are namedtuples just as memory efficient as regular tuples?
Yes
123
What does deduplicate mean?
Eliminate duplicate or redundant information from (something, especially computer data). "They can deduplicate files uploaded by many different users to keep costs lower than otherwise possible"
124
What is the acronym for the order of operations in math (and Python)?
PEMDAS
125
How do you create a multi-line comment in Python?
There is no multi-line comment capability in Python. Due to the existence of docstrings a lot of people are confused about the use of """ elsewhere. This is wrong. Python only has one way of doing comments and that is using #
126
Do you have to import anything to use an array in Python?
Yes The array or numpy module
127
What does it mean that a list is "ordered"?
It means that items in a list appear in a specific order, which enables us to use an index to access to any item It does not mean the items are ordered in the English language sense of the world, such as from greatest to least, or longest to shortest, etc.
128
What are the differences between arrays and lists?
You need to import array or numpy to use arrays Arrays need to be declared. Lists don't. Arrays can store data very compactly and are more efficient for storing large amounts of data Arrays are great for numerical operations. For example, you can divide each element of an array by the same number with just one line of code: import numpy array = numpy.array([3, 6, 9, 12]) division = array/3 print(division) # [1. 2. 3. 4.] If you try the same with a list, you'll get an error
129
The dot notation turtle.Turtle means?
The Turtle type that is defined within the turtle module. You should read this as: “In the module turtle, access the Python element called Turtle”
130
What is the term for using a method of a class?
Invoking a method. We use the verb invoke to mean activate the method. Invoking a method is done by putting parentheses after the method name, with some possible arguments
131
What is iteration?
looping through a set of instructions
132
In this code, what is the term for kids? for kids in school:
the Loop Variable
133
loop terminator, compound statement
look up
134
How would you write code that asks the user for a number and then stores it in a variable called x?
x = input("enter number")
135
What is control flow?
the flow of execution
136
What is the difference between arguments and parameters?
Parameters are part of the function definition, and don't contain any actual data Arguments are what we pass to a function when we invoke it, and do contain data Arguments get assigned to the parameters in the function definition
137
What is a fruitful function?
A function that returns something
138
Do non-fruitful functions technically return something?
Yes, all Python functions return the value None unless there is an explicit return statement with a value other than None.
139
What is a function lifetime?
From when a function is run to when it exits
140
If python cannot find a local variable it needs inside a function, what happens?
It will look to see if the variable exists outside the function (global variable)
141
When a local variable has the same name as a global variable
We say that the local shadows the global. A shadow means that the global variable cannot be accessed by Python because the local variable will be found first.
142
What is the accumulator pattern?
Iterating the updating of a variable initialize the accumulator variable repeat: modify the accumulator variable ``` # instead of using powers (**) for counter in range(x): runningtotal += x ```
143
What is Additive Identity?
Additive identity is a number, which when added to any number, gives the sum as the number itself. For any set of numbers, that is, all integers, rational numbers, complex numbers, the additive identity is 0. It is because when you add 0 to any number; it doesn't change the number and keeps its identity
144
What is Multiplicative Identity?
Multiplicative identity is a number, which when multiplied by any number, gives the answer as the number itself. For any set of numbers, that is, all integers, rational numbers, complex numbers, the Multiplicative identity is 1. It is because when you multiply 0 by any number; it doesn't change the number and keeps its identity
145
What is functional decomposition?
This process of breaking a problem into smaller subproblems
146
What is Generalization?
A way of quickly solving new problems based on previous problems we have solved. We can take an algorithm that solves some specific problem and adapt it so that it solves a whole class of similar problems ``` def drawRectangle(t, w, h): """Get turtle t to draw a rectangle of width w and height h.""" for i in range(2): t.forward(w) t.left(90) t.forward(h) t.left(90) ``` ``` def drawSquare(tx, sz): # a new version of drawSquare drawRectangle(tx, sz, sz) ```
147
Do function definitions get executed even if they are not called?
Yes, the function DEFINITION (or header) only however, not the function body
148
Define an Expression vs. a Statement
An Expression is a combination of values and functions that are combined and interpreted by the compiler to create a new value A Statement which is just a standalone unit of execution and doesn’t return anything.
149
In the code below, which part is the expression? x = 1 + y + math.pow(6)
1 + y + math.pow(6)
150
In the code below, which part is the statement? x = 1 + y + math.pow(6)
The entire thing x = 1 + y + math.pow(6)
151
Is math.pow(6) a statement?
Yes
152
Before the Python interpreter executes your program, it defines a few special variables. One of those variables is called __name__ and it is automatically set to the string value "__main__" when the program is being executed by itself in a standalone fashion. On the other hand, if the program is being imported by another program, then the __name__ variable is set to the name of that module
if __name__ == "__main__": | main()
153
What is incremental development?
The goal of incremental development is to avoid long debugging sessions by adding and testing only a small amount of code at a time
154
What's a common naming convention for boolean functions?
Names that sound like yes/no questions isDivisible()
155
Is it legal to have a statement be evaluated in the same line as the return keyword?
Yes return x = y < z
156
tuple = ("c# corner", ".net", "python", "asp", "mvc") | print(tuple[1:3])
("net", "python") remember the last number in slice is not inclusive
157
What method can you use to get all the keys of a dictionary?
.keys()
158
How would you delete an item from a list based on its value?
.remove("value")
159
How would you place a value into a list at the 6th index?
.insert(6,"value")
160
How would you get the index of an item in a list based on its value?
.index("value")
161
What is the output of print(list[-2]) if list=[50, 1, 16, 2, 20]? 
-2
162
What is the output of print(2 in list) if list = [50, 1, 16, 2, 20]?
True
163
What is the difference between del() and remove() methods of the list? 
remove() method is used to delete a single element from the list del() method is used to delete the whole list
164
How will you replace all the occurrences of the old substring in str with a new string?
str1 = str.replace("what to look for", "what to replace it with")
165
How would you convert a string to a tuple?
``` str = "abc" tup = tuple(str) ```
166
How would you create a dictionary, using tuples in Python?
``` tuple = (("name", "ajay"), ("sex", "male")) dict = dict(tuple) ```