Python Badge
Q77. How is comment created?
#
Q87. In Python, when using sets, you use ___ to calculate the intersection between two sets and ___ to calculate the union.
& ; |
Q7. What built-in list method would you use to remove items from a list?
.pop( ) method my_list = [1,2,3] my_list.pop(0) my_list >>>[2,3]
Q86. What would this recursive function print if it is called with no parameters? def count_recursive(n=1): if n > 3: return print(n) count_recursive(n + 1)
1 2 3
Q99. Suppose you have a string variable defined as y="stuff;thing;junk;". What would be the output from this code? Z = y.split(';') len(z)
4 explanation y="stuff;thing;junk" len(z) ==> 3 y="stuff;thing;junk;" len(z) ==> 4
Q93. Which statement about the class methods is true?
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.
Q50. What statement about the class methods is true?
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.
Q54. Describe the functionality of a deque.
A deque adds items at either or both ends, and remove items at either or both ends. Explanation - deque is used to create block chanin and in that there is first in first out approch, which means the last element to enter will be the first to leave.
Q80. Describe the functionality of a queue?
A queue adds items to either end and removes items from either end.
Q36. What is key difference between a set and a list?
A set is an unordered collection unique items. A list is an ordered collection of non-unique items.
Q37. 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.
Q64. What is the runtime complexity of adding an item to a stack and removing an item from a stack?
Add items to a stack in O(1) time and remove items from a stack in O(1) time.
Q1: What is an abstract class?
An abstract class exists only so that other "concrete" classes can inherit from the abstract class.
Q40. 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.
Q73. What does a generator return?
An iterable object
Q5. What are attributes?
Attributes are a way to hold data or describe a state for a class or an instance of a class.
Q74. 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
Q34. What is the algorithmic paradigm of quick sort?
Divide and conquer
Q25. If you don't explicitly return a value from a function, what happens?
If the return keyword is absent, the function will return None.
Q63. Why would you use mixin?
If you have many classes that all need to have the same functionality, you'd use a mixin to define that functionality.
Q14. 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.
Q82. 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.
Q18. What is an instance method?
Instance methods can modify the state of an instance or the state of its parent class.
Q24. 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. Explanation: - The synax for map() function is list(map(function,iterable). the simple area finder using map would be like this import math radius = [1,2,3] area = list(map(lambda x: round(math.pi*(x**2), 2), radius)) area >>> [3.14, 12.57, 28.27]
Q21. 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.
Q26. What is the purpose of the pass statement in Python?
It is a null operation used mainly as a placeholder in functions, classes, etc.
Q20. Which statement describes the object-oriented programming concept of encapsulation?
It protects the data from outside interference. A parent class is encapsulated and no data from the parent class passes on to the child class. It keeps data and the methods that can manipulate that data in one place.
Q88. What will this code fragment return? import numpy as np np.ones([1,2,3,4,5])
It returns a 5-dimensional array of size 1x2x3x4x5 filled with 1s.
Q12. What built-in Python data type is commonly used to represent a stack?
List. You can only build a stack from scratch
Q71. 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.
Q17. Which of these is NOT a characteristic of namedtuples?
No import is needed to use namedtuples because they are available in the standard library. **We need to import it using from collections import namedtuple **
Q35. What is runtime complexity of the list's built-in .append() method?
O(1)
Q9. What is the runtime of accessing a value in a dictionary by using its key?
O(1), also called constant time.
Q4. What statement about static methods is true?
Static methods serve mostly as utility methods or helper methods, since they can't access or modify a class's state.
Q72. Which statement about static method is true?
Static methods serve mostly as utility or helper methods, since they cannot access or modify a class's state.
Q45. 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. class test: def __init__(self): print('I came here without your permission lol') pass t1 = test() >>> 'I came here without your permission lol'
Q32. 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. Explanation - all() returns true if all in the list are True, see example below test = [True,False,False,False] if all(test) is True: print('Yeah all are True') else: print('There is an imposter') >>> There is an imposter
Q46. What is meant by the phrase "space complexity"?Q46. What is meant by the phrase "space complexity"?
The amount of space taken up in memory as a function of the input size
Q51. What does it mean for a function to have linear runtime?
The amount of time it takes the function to complete grows linearly as the input size increases.
Q2. What happens when you use the build-in function any( ) on a list?
The any( ) function returns True if any item in the list evaluates to True. Otherwise, it returns False. if any([True, False, False, False]) == True: print('Yes, there is True') >>> Yes, there is True
Q96. 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.
Q30. Assuming the node is in a singly linked list, 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.
Q44. What value would be returned by this check for equality? 5 != 6
True
Q68. 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.
Q59. When would you use a for loop?
When you need to check every element in an iterable of known length.
Q67. 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.
Q61. 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.
Q13. 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')]
Q100. What is the output of this code? num_list = [1,2,3,4,5] num_list.remove(2) print(num_list)
[1,3,4,5] explanation: num_list = [1,2,3,4,5] num_list.pop(2) [1,2,4,5] num_list.remove(2) [1,3,4,5]
Q98. What is the output of this code? (NumPy has been imported as np.)? a = np.array([1,2,3,4]) print(a[[False, True, False, False]])
[2]
Q38. What does this function print? def print_alpha_nums(abc_list, num_list): for char in abc_list: for num in num_list: print(char, num) return print_alpha_nums(['a', 'b', 'c'], [1, 2, 3])
a 1 a 2 a 3 b 1 b 2 b 3 c 1 c 2 c 3
Q90. what will this command return? {x for x in range(100) if x%3 == 0}
a set of all the multiples of 3 less then 100
Q65. Which statement accurately describes how items are added to and removed from a stack?
a stacks adds items to the top and removes items from the top.
Q27. What is the term used to describe items that may be passed into a function?
arguments
Q15. What is the correct syntax for defining a class called "Game", if it inherits from a parent class called "LogicGame"?
class Game(LogicGame): pass
Q95. What is the correct syntax for defining a class called Game?
class Game: pass
Q94. What file is imported to use dates in python?
datetime
Q56. What is the correct syntax for defining an __init__( ) method that takes no parameters?
def __init__(self): pass
Q60. What is the most self-descriptive way to define a function that calculates sales tax on a purchase?
def calculate_sales_tax(subtotal): pass
Q52. What is the proper way to define a function?
def get_max_num(list_of_nums): # body of function goes here
Q75. What is the correct syntax of creating an instance method?
def get_next_card(self): # method body goes here
Q11. What is the correct way to write a doctest?
def sum(a, b): """ >>> sum(4, 3) 7 >>> sum(-4, 5) 1 """ return a + b explanation - use ''' to start the doc and add output of the cell after >>>
Q28. Which collection type is used to associate values with unique keys?
dictionary
Q43. Review the code below. What is the correct syntax for changing the price to 1.5? fruit_info = { 'fruit': 'apple', 'count': 2, 'price': 3.5 }
fruit_info ['price'] = 1.5
Q83. What is the correct syntax for adding a key called variety to the fruit_info dictionary that has a value of Red Delicious?
fruit_info['variety'] = 'Red Delicious'
Q48. 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()]
Q76. What is the correct way to call a function?
get_max_num([57, 99, 31, 18])
Q79. What will happen if you use a while loop and forget to include logic that eventually causes the while loop to stop?
infinite loop
Q3. What data structure does a binary tree degenerate to if it isn't balanced properly?
linked List
Q22. What built-in Python data type is best suited for implementing a queue?
list
This code provides the ___ of the list of numbers num_list = [21,13,19,3,11,5,18] num_list.sort() num_list[len(num_list)//2]
median
Q23. What is the correct syntax for instantiating a new object of the type Game?
my_game = Game()
Q97. What is the correct syntax for calling an instance method on a class named Game?
my_game = Game() self.my_game.roll_dice()
Q78. What is the correct syntax for replacing the string apple in the list with the string orange? my_list = ['kiwi', 'apple', 'banana']
my_list[1] = 'orange'
Q55. What is the correct syntax for creating a variable that is bound to a set?
my_set = {0, 'apple', 3.5}
Q19. 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.")
Q69. What is the correct way to run all the doctests in a given file from the command line?
python3 -m doctest <filename>
Q16. What is the purpose of the "self" keyword when defining or calling instance methods?
self refers to the instance whose method was called. class my_secrets: def __init__(self, password): self.password = password pass instance = my_secrets('1234') instance.password >>>'1234'
Q29. 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
Q84. When would you use a while loop?
when you want some code to continue running as long as some condition is true i = 1 while i<6: print('Countdown:',i) i = i + 1
Q42. What symbol(s) do you use to assess equality between two elements?
= =
Q33. What is the correct syntax for calling an instance method on a class named Game?
>>> dice = Game() >>> dice.roll()
Q66. 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.
Q89. You encounter a FileNotFoundException while using just the filename in the open function. What might be the easiest solution?
Copy the file to the same directory as where the script is running from
Q57. Which of the following is TRUE About how numeric data would be organized 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.
Q62. 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.
Q58. Why would you use a decorator?
You use the decorator to alter the functionality of a function without having to modify the functions code.
Q70. What is a lambda function ?
a small, anonymous function that can take any number of arguments but has only expression to evaluate Explanation: the lambda notation is basically an anonymous function that can take any number of arguments with only single expression (i.e, cannot be overloaded). It has been introduced in other programming languages, such as C++ and Java. The lambda notation allows programmers to "bypass" function declaration.
Q41. What does calling namedtuple on a collection type return?
a tuple subclass with iterable named fields Example import math radius = [1,2,3] area = list(map(lambda x: round(math.pi*(x**2), 2), radius)) area >>> [3.14, 12.57, 28.27]
Q10. What is the correct syntax for defining a class called Game, if it inherits from a parent class called LogicGame?
class Game(LogicGame): pass Explanation: The parent class which is inherited is passed as an argument to the child class.
Q85. What is the correct syntax for defining an __init__() method that sets instance-specific attributes upon creation of a new class instance?
def __init__(self, attr1, attr2): self.attr1 = attr1 self.attr2 = attr2 Explanation: When instantiating a new object from a given class, the __init__() method will take both attr1 and attr2, and set its values to their corresponding object attribute, that's why the need of using self.attr1 = attr1 instead of attr1 = attr1.
Q39. Correct representation of doctest for function in Python
def sum(a, b): """ >>> a = 1 >>> b = 2 >>> sum(a, b) 3 """ return a + b Explanation: Use """ to start and end the docstring and use >>> to represent the output. If you write this correctly you can also run the doctest using build-in doctest module
Q49. What is the purpose of the self keyword when defining or calling methods on an instance of an object?
elf refers to the instance whose method was called. Explanation: - Try running the example of the Q45 without passing self argument inside the __init__, you'll understand the reason. You'll get the error like this __init__() takes 0 positional arguments but 1 was given, this means that something is going inside even if haven't specified, which is instance itself.
Q47. What is the correct syntax for creating a variable that is bound to a dictionary?
fruit_info = {'fruit': 'apple', 'count': 2, 'price': 3.5}
Q31. Given the following three list, 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
Q53. According to the PEP 8 coding style guidelines, how should constant values be named in Python?
in all caps with underscores separating words -- e.g. MAX_VALUE = 255
Q81. 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.")
Q91. What does the // operator in Python 3 allow you to do?
perform integer division
Q8. What is one of the most common use of Python's sys library?
to capture command-line arguments given at a file's runtime
Q6. What is the term to describe this code? count, fruit, price = (2, 'apple', 3.5)
tuple unpacking