honPyt Flashcards
While using Python in interactive mode, which variable is the default prompt for continuation lines?
…
While using Python in interactive mode, which variable holds the value of the last printed expression?
_ (underscore)
With the variable assignment name=”Python”, what will be the output of print(name[-1])?
“n”
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)
(‘Welcome Joe’, ‘Good Bye Joe’)
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)
1.5
1
5
What does the “//” operator do?
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)
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])
ether
water
fire
earth
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)
0
10
20
(this only returns the first loop, as generator data can only be used once)
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’, ‘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
What would be the output of this code?
x = 3 + 2j
y = 3 - 2j
z = x + y
print(z)
(6+0j)
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)
0
1
2
Done!
What is the slicing operator in Python?
:
What does trunc() do?
trunc() rounds down positive floats, and rounds up negative floats
math. trunc(3.5) # 3
math. trunc(-3.5) # -3
Can you use remove() to delete an element from an array by giving it an index number?
No
What keyword can be used to remove an item from a list based on its index?
del
numbers = [50, 60, 70, 80]
del numbers[1] # numbers = [50, 70, 80]
How would you use pop() to remove the first element of an array?
pop(0)
numbers = [50, 60, 70, 80]
numbers.pop(0) # [60, 70, 80]
What would be the output of this code?
a, b, c, d = 1, ‘cat’, 6, 9
print(c)
6
What would be the output of this code?
a, b, c, d = 1
print(c)
TypeError: cannot unpack non-iterable int object
What is the lambda keyword used for?
It is used for creating simple anonymous functions
What keyword can be used to force a particular exception to occur?
raise
Which module will process command line arguments for a Python script?
os
What is the syntax of a lambda function on Python?
lambda arguments: expression
How would you make a deep copy of an array?
Use copy()
arr2 = arr1.copy()
Using filter() how would you use lambda to select all numbers over 5 from array my_list?
filter(lambda x: x > 5, my_list)
Can lambda only be used for numeric expressions?
Yes
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])
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
Which function will return DirEntry objects instead of strings while trying to list the contents of the directory?
os.scandir()
What is an abstract class?
An abstract class exists only so that other “concrete” classes can inherit from the abstract class
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
What data structure does a binary tree degenerate to if it isn’t balanced properly?
linked list
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
What are attributes?
Attributes are a way to hold data, or describe a state for a class or an instance of a class
What is the term to describe this code?
count, fruit, price = (2, ‘apple’, 3.5)
tuple unpacking
What built-in list method would you use to remove items from a list?
pop()
What is one of the most common use of Python’s sys library?
to capture command-line arguments given at a file’s runtime
What is the runtime of accessing a value in a dictionary by using its key?
O(1), also called constant time
What is the correct syntax for defining a class called Game?
class Game:
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
What built-in Python data type is commonly used to represent a stack?
list
you can only build a stack from scratch
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’)]
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
What is the correct syntax for defining a class called “Game”, if it inherits from a parent class called “LogicGame”?
class Game(LogicGame):
What is the purpose of the “self” keyword when defining or calling instance methods?
self refers to the instance whose method was called
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
What is an instance method?
Instance methods can modify the state of an instance or the state of its parent class
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.”)
Is it true that encapsulation only allows data to be changed by methods?
No
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
What built-in Python data type is commonly used to represent a queue?
list
What is the correct syntax for instantiating a new object of the type Game?
x = Game()
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
If there is no return keyword in a function, what happens?
If the return keyword is absent, the function will return None
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
What is the term used to describe items that may be passed into a function?
arguments
Which collection type is used to associate values with unique keys?
dictionary
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
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
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)
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
What is the correct syntax for calling an instance method on a class named Game?
> > > dice = Game()
|»_space;> dice.roll()
What is the algorithmic paradigm of quick sort?
backtracking
dynamic programming
decrease and conquer
divide and conquer
divide and conquer
What is runtime complexity of the list’s built-in .append() method?
O(1), also called constant time
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
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
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
What is the correct syntax for calling an instance method on a class named DiceGame?
my_var = DiceGame()
my_var.roll_dice()
Correct representation of doctest for function in Python
def sum(a, b): """ >>> a = 1 >>> b = 2 >>> sum(a, b) 3 """
return a + b
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
What does calling namedtuple on a collection type return?
a tuple subclass with iterable named fields
What symbol(s) do you use to assess equality between two elements?
==
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
What value would be returned by this check for equality?
5 != 6
True
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
What is meant by the phrase “space complexity”?
The amount of space taken up in memory as a function of the input size
What is the correct syntax for creating a variable that is bound to a dictionary?
fruit_info = {‘fruit’: ‘apple’, ‘count’: 2, ‘price’: 3.5}
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()]
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
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
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
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):
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
Describe the functionality of a deque.
A deque adds items at either or both ends, and remove items at either or both ends
What is the correct syntax for creating a variable that is bound to a set?
myset = {0, ‘apple’, 3.5}
What is the correct syntax for defining an __init__() method that takes no parameters and returns nothing?
def \_\_init\_\_(self): pass
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
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
Why would you use a decorator?
You use a decorator to alter the functionality of a function, without having to modify the functions code
When would you use a for loop?
When you need to check every element in an iterable of known length
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
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
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
What is the runtime complexity of adding an item to a stack and removing an item from a stack?
O(1) time
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
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
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
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
What is the correct way to run all the doctests in a given file from the command line?
python3 filename . py
What is a lambda function?
a small, anonymous function that can take any number of arguments, but has only 1 expression to evaluate
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
How are static methods used?
Static methods serve mostly as utility or helper methods, since they cannot access or modify a class’s state
What does a generator return?
An iterable object, that does not exist in memory
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
What is the correct syntax of creating an instance method?
def get_next_card(self):
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
What is the correct way to call a function?
get_max_num([57, 99, 31, 18])
How is a single line comment created?
#
What is the correct syntax for replacing the string “apple” in the my_list with the string “orange”?
my_list[1] = ‘orange’
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
Describe the functionality of a deque.
A deque adds items to either end, and removes items from either end
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.”)
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
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)
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
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
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 “-“
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
What would you use to chop a string into blocks by a space?
split(‘ ‘)
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”
Is it true that no import is needed to use namedtuples?
No
from collections import namedtuple
Can each member of a namedtuple object be indexed to directly, just like in a regular tuple?
Yes
Are namedtuples just as memory efficient as regular tuples?
Yes
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”
What is the acronym for the order of operations in math (and Python)?
PEMDAS
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 #
Do you have to import anything to use an array in Python?
Yes
The array or numpy module
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.
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
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”
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
What is iteration?
looping through a set of instructions
In this code, what is the term for kids?
for kids in school:
the Loop Variable
loop terminator, compound statement
look up
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”)
What is control flow?
the flow of execution
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
What is a fruitful function?
A function that returns something
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.
What is a function lifetime?
From when a function is run to when it exits
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)
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.
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
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
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
What is functional decomposition?
This process of breaking a problem into smaller subproblems
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)
Do function definitions get executed even if they are not called?
Yes, the function DEFINITION (or header) only however, not the function body
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.
In the code below, which part is the expression?
x = 1 + y + math.pow(6)
1 + y + math.pow(6)
In the code below, which part is the statement?
x = 1 + y + math.pow(6)
The entire thing
x = 1 + y + math.pow(6)
Is math.pow(6) a statement?
Yes
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()
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
What’s a common naming convention for boolean functions?
Names that sound like yes/no questions
isDivisible()
Is it legal to have a statement be evaluated in the same line as the return keyword?
Yes
return x = y < z
tuple = (“c# corner”, “.net”, “python”, “asp”, “mvc”)
print(tuple[1:3])
(“net”, “python”)
remember the last number in slice is not inclusive
What method can you use to get all the keys of a dictionary?
.keys()
How would you delete an item from a list based on its value?
.remove(“value”)
How would you place a value into a list at the 6th index?
.insert(6,”value”)
How would you get the index of an item in a list based on its value?
.index(“value”)
What is the output of
print(list[-2]) if list=[50, 1, 16, 2, 20]?
-2
What is the output of
print(2 in list) if list = [50, 1, 16, 2, 20]?
True
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
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”)
How would you convert a string to a tuple?
str = "abc" tup = tuple(str)
How would you create a dictionary, using tuples in Python?
tuple = (("name", "ajay"), ("sex", "male")) dict = dict(tuple)