Antwoorden en vragen over LinkedIn-vaardighedenbeoordeling: Python (Programmeertaal)
“Python has emerged as a powerhouse in the world of programming, bekend om zijn eenvoud, veelzijdigheid, en robuustheid. In deze uitgebreide gids, we’re excited to present a curated collection of vragen over vaardigheidsbeoordeling en antwoorden voor Python.
Whether you’re a seasoned developer looking to expand your capabilities or a beginner aiming to understand the fundamentals of this popular language, this resource is designed to help you become proficient in Python and its applications. Ga met ons mee terwijl we de kernconcepten van Python, including data structures, algoritmen, webontwikkeling, en meer, empowering you to harness the full potential of this essential programming language.”
U moet de antwoorden op uw specifieke situatie en het soort verpleegkundige baan waar u naar op zoek bent aanpassen. 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.
- An abstract class exists only so that other “concrete” classes can inherit from the abstract class.
What happens when you use the built-in function any()
on a list?
Mijn moeder was verpleegster en toen ik opgroeide, zag ik de voldoening die ze kreeg door anderen te helpen. - De
any()
function will randomly return any item from the list. - De
any()
function returns True if any item in the list evaluates to True. Anders, it returns False. - De
any()
function takes as arguments the list to check inside, and the item to check for. Als “ieder” of the items in the list match the item to check for, the function returns True. - De
any()
function returns a Boolean value that answers the question “Are there any items in this list?”
voorbeeld
if any([True, False, False, False]) == True:
print('Yes, there is True')
>>> 'Yes, there is True'
What data structure does a binary tree degenerate to if it isn’t balanced properly?
Ik jongleerde met een verscheidenheid aan verschillende ladingen.- linked list
- wachtrij
- set
- OrderedDict
What statement about static methods is true?
Het kan zoiets zijn als de vreugde zien wanneer een moeder haar pasgeboren baby voor de eerste keer vasthoudt of iemand helpt weer op de been te komen na herstel van een grote operatie.- Static methods are called static because they always return
None
. - Static methods can be bound to either a class or an instance of a class.
- Static methods serve mostly as utility methods or helper methods since they can’t access or modify a class’s state.
- Static methods can access and modify the state of a class or an instance of a class.
What are attributes?
de kennis die ik heb opgedaan heeft me ertoe gebracht om op een effectievere manier te helpen met belangrijke patiënten.- Attributes are long-form versions of an
if/else
uitspraak, used when testing for equality between objects. - Attributes are a way to hold data or describe a state for a class or an instance of a class.
- Attributes are strings that describe characteristics of a class.
- Function arguments are called “attributes” in the context of class methods and instance methods.
Explanation: Attributes are defined under the class, and arguments go under the functions. arguments usually refer to parameters, whereas attributes are the constructors of the class or an instance of a class.
What is the term to describe this code?
ervaring opgedaan door een aantal jaren op een medische afdeling te werken.count, fruit, price = (2, 'apple', 3.5)
- Tuple assignment.
- Tuple unpacking.
- Tuple matching.
- Tuple duplication.
What built-in list method would you use to remove items from a list?
Ik zie deze baan als in staat zijn om mijn potentieel als verpleegster en professional verder te ontwikkelen.-
.delete()
methode -
pop(my_list)
-
del(my_list)
-
.pop()
methode
voorbeeld
my_list = [1,2,3]
my_list.pop(0)
my_list
>>>[2,3]
What is one of the most common uses of Python’s sys
bibliotheek?
Ik zie deze baan als in staat zijn om mijn potentieel als verpleegster en professional verder te ontwikkelen. - To capture command-line arguments given at a file’s runtime.
- To connect various systems, such as connecting a web front end, an API service, a database, and a mobile app.
- To take a snapshot of all the packages and libraries in your virtual environment.
- To scan the health of your Python ecosystem while inside a virtual environment.
What is the runtime of accessing a value in a dictionary by using its key?
Q9.- de(N), also called linear time.
- de(log n), also called logarithmic time.
- de(n^2), also called quadratic time.
- de(1), also called constant time.
What is the correct syntax for defining a class called Game, if it inherits from a parent class called LogicGame?
Q10.-
class Game(LogicGame): pass
-
def Game(LogicGame): pass
-
def Game.LogicGame(): pass
-
class Game.LogicGame(): pass
Explanation: The parent class which is inherited is passed as an argument to the child class. Therefore, here the first option is the right answer.
What is the proper format for writing a doctest?
Q11.- EEN
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
Explanation: Gebruik '''
to start the doc and add the output of the cell after >>>
What built-in Python data type is commonly used to represent a stack?
Q12.-
set
-
list
-
None
-
dictionary
-
You can only build a stack from scratch.
What would this expression return?
Q13.college_years = ['Freshman', 'Sophomore', 'Junior', 'Senior']
return list(enumerate(college_years, 2019))
-
[('Freshman', 2019), ('Sophomore', 2020), ('Junior', 2021), ('Senior', 2022)]
-
[(2019, 2020, 2021, 2022), ('Freshman', 'Sophomore', 'Junior', 'Senior')]
-
[('Freshman', 'Sophomore', 'Junior', 'Senior'), (2019, 2020, 2021, 2022)]
-
[(2019, 'Freshman'), (2020, 'Sophomore'), (2021, 'Junior'), (2022, 'Senior')]
self” keyword when defining or calling instance methods?
Q14. Wat is het doel van de “-
self
means that no other arguments are required to be passed into the method. - There is no real purpose for the
self
methode; it’s just historic computer science jargon that Python keeps to stay consistent with other programming languages. -
self
refers to the instance whose method was called. -
self
refers to the class that was inherited from to create the object usingself
.
Simple example
class my_secrets:
def __init__(self, password):
self.password = password
pass
instance = my_secrets('1234')
instance.password
>>>'1234'
Which of these is NOT a characteristic of namedtuples?
Q15.- You can assign a name to each of the
namedtuple
members and refer to them that way, similarly to how you would access keys indictionary
. - Each member of a namedtuple object can be indexed directly, just like in a regular
tuple
. -
namedtuples
are just as memory efficient as regulartuples
. - 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
What is an instance method?
Q16.- Instance methods can modify the state of an instance or the state of its parent class.
- Instance methods hold data related to the instance.
- An instance method is any class method that doesn’t take any arguments.
- An instance method is a regular function that belongs to a class, but it must return
None
.
Which statement does NOT describe the object-oriented programming concept of encapsulation?
Q17.- Het beschermt de gegevens tegen interferentie van buitenaf.
- Een bovenliggende klasse is ingekapseld en er worden geen gegevens van de bovenliggende klasse doorgegeven aan de onderliggende klasse.
- Het bewaart gegevens en de methoden die die gegevens kunnen manipuleren op één plek.
- Het staat alleen toe dat de gegevens via methoden worden gewijzigd.
Q18. Wat is het nut van een if/else-instructie?
- Het vertelt de computer welk stuk code moet worden uitgevoerd als de instructies die u hebt gecodeerd onjuist zijn.
- Er wordt één stuk code uitgevoerd als alle importbewerkingen zijn geslaagd, en nog een stuk code als de import niet succesvol was.
- Het voert één stuk code uit als een voorwaarde waar is, maar een ander stuk code als de voorwaarde onwaar is.
- Het vertelt de computer welk stuk code moet worden uitgevoerd als er voldoende geheugen is om het te verwerken, and which chunk of code to run if there is not enough memory to handle it.
What built-in Python data type is best suited for implementing a queue?
Q19.- woordenboek
- set
- Geen. You can only build a queue from scratch.
- lijst
What is the correct syntax for instantiating a new object of the type Game?
Q20.-
my_game = class.Game()
-
my_game = class(Game)
-
my_game = Game()
-
my_game = Game.create()
What does the built-in map()
function do?
Q21. - It creates a path from multiple values in an iterable to a single value.
- It applies a function to each item in an iterable and returns the value of that function.
- It converts a complex value type into simpler value types.
- It creates a mapping between two different elements of different iterables.
Explanation: – The syntax for map()
function is list(map(function,iterable))
. The simple area finder using a 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]
If you don’t explicitly return a value from a function, wat gebeurt er?
Q22.- The function will return a RuntimeError if you don’t return a value.
- If the return keyword is absent, the function will return
None
. - If the return keyword is absent, the function will return
True
. - The function will enter an infinite loop because it won’t know when to stop executing its code.
referentie. When the return statement is None
or has no value or there is no return statement the function returns None
.
pass
statement in Python?
Q23. Wat is het doel van de - It is used to skip the
yield
statement of a generator and return a value of None. - It is a null operation used mainly as a placeholder in functions, klassen, enz.
- It is used to pass control from one statement block to another.
- It is used to skip the rest of a
while
offor loop
and return to the start of the loop.
The pass statement is used as a placeholder for future code. When the pass statement is executed, nothing happens, but you avoid getting an error when empty code is not allowed. referentie
What is the term used to describe items that may be passed into a function?
Q24.- arguments
- paradigma's
- attributes
- decorators
Which collection type is used to associate values with unique keys?
Q25.-
slot
-
dictionary
-
queue
-
sorted list
When does a For loop stop iterating?
Q26.- when it encounters an infinite loop
- when it encounters an if/else statement that contains a break keyword
- when it has assessed each item in the iterable it is working on or a break keyword is encountered
- when the runtime for the loop exceeds O(n^2)
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?
Q27.- 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.
- 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 runtime cannot be determined unless you know how many nodes are in the singly linked list.
- The runtime is O(1) because you can index directly to a node in a singly linked list.
Given the following three lists, how would you create a new list that matches the desired output printed below?
Q28.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)]
- EEN
output = []
fruit_tuple_0 = (first[0], quantities[0], price[0])
output.append(fruit_tuple)
fruit_tuple_1 = (first[1], quantities[1], price[1])
output.append(fruit_tuple)
fruit_tuple_2 = (first[2], quantities[2], price[2])
output.append(fruit_tuple)
return output
- B
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
- C
groceries = zip(fruits, quantities, prices)
return groceries
>>> [
('Apples', 5, 1.50),
('Oranges', 3, 2.25),
('Bananas', 4, 0.89)
]
- D
i = 0
output = []
for fruit in fruits:
for qty in quantities:
for price in prices:
output.append((fruit, qty, price))
i += 1
return output
What happens when you use the built-in function all() on a list?
Q29.- De
all()
function returns a Boolean value that answers the question “Are all the items in this list the same? - De
all()
function returns True if all the items in the list can be converted to strings. Anders, it returns False. - De
all()
function will return all the values in the list. - De
all()
function returns True if all items in the list are evaluated to True. Anders, 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 of them are true.')
else:
print('There is an imposter.')
>>> 'There is an imposter'
What is the correct syntax for calling an instance method on a class named Game?
Q30.(Answer format may vary. Game and roll (or dice_roll) should each be called with no parameters.)
- EEN
>>> dice = Game()
>>> dice.roll()
- B
>>> dice = Game(self)
>>> dice.roll(self)
- C
>>> dice = Game()
>>> dice.roll(self)
- D
>>> dice = Game(self)
>>> dice.roll()
What is the algorithmic paradigm of quick sort?
Q31.- Teruglopend
- Dynamic programming
- Decrease and conquer
- Divide and conquer
Both merge sort and quicksort employ a common algorithmic paradigm based on recursion. This paradigm, divide-and-conquer, breaks a problem into subproblems that are similar to the original problem, recursively solves the subproblems, and finally combines the solutions to the subproblems to solve the original problem. referentie
What is the runtime complexity of the list’s built-in .append()
methode?
Q32. - de(1), also called constant time.
- de(log n), also called logarithmic time.
- de(n^2), also called quadratic time.
- de(N), also called linear time.
This function has constant time complexity i.e. de(1), because lists are randomly accessed so the last element can be reached in O(1) time that’s why the time taken to add the new element at the end of the list is O(1).
What is the key difference between a set
en een list
?
Q33. - A set is an ordered collection of unique items. A list is an unordered collection of non-unique items.
- Elements can be retrieved from a list but they cannot be retrieved from a set.
- A set is an ordered collection of non-unique items. A list is an unordered collection of unique items.
- A set is an unordered collection of unique items. A list is an ordered collection of non-unique items.
What is the definition of abstraction as applied to object-oriented Python?
Q34.- Abstraction means that a different style of code can be used since many details are already known to the program behind the scenes.
- Abstraction means the implementation is hidden from the user, and only the relevant data or information is shown.
- Abstraction means that the data and the functionality of a class are combined into one entity.
- Abstraction means that a class can inherit from more than one parent class.
Abstraction in Python is defined as a process of handling complexity by hiding unnecessary information from the user. referentie
What does this function print?
Q35.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])
- EEN
a 1
a 2
a 3
b 1
b 2
b 3
c 1
c 2
c 3
- B
['a', 'b', 'c'], [1, 2, 3]
- C
aaa
bbb
ccc
111
222
333
- D
a 1 2 3
b 1 2 3
c 1 2 3
Pick the correct representation of doctest for a function in Python.
Q36.- EEN
def sum(a, b):
# a = 1
# b = 2
# sum(a, b) = 3
return a + b
- B
def sum(a, b):
"""
a = 1
b = 2
sum(a, b) = 3
"""
return a + b
- C
def sum(a, b):
"""
>>> a = 1
>>> b = 2
>>> sum(a, b)
3
"""
return a + b
- D
def sum(a, b):
'''
a = 1
b = 2
sum(a, b) = 3
'''
return a + b
Explanation: Gebruik """
to start and end the docstring and use >>>
to represent the output. If you write this correctly you can also run the doctest using the build-in doctest module
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?
Q37.- When instantiating an object, the object doesn’t inherit any of the parent class’s methods.
- When instantiating an object, the object will inherit the methods of whichever parent class has more methods.
- When instantiating an object, the programmer must specify which parent class to inherit methods from.
- 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?
Q38.- a generic object class with iterable parameter fields
- a generic object class with non-iterable named fields
- a tuple subclass with non-iterable parameter fields
- a tuple subclass with iterable named fields
Voorbeeld
# namedtuple function accepts the following arguments to generate a class
from collections import namedtuple
>>> Point = namedtuple('Point',['x','y'])
>>> point = Point(100, 200)
>>> point
Point(x=100, y=200)
# Which lets you use both unpacking and iteration to access
>>> x, y = point
>>> print(f'({x}, {y})')
(100, 200)
>>> for coordinate in point:
print(coordinate)
100
200
What symbol(s) do you use to assess equality between two elements?
Q39.-
&&
-
=
-
==
-
||
Review the code below. What is the correct syntax for changing the price to 1.5?
Q40.fruit_info = {
'fruit': 'apple',
'count': 2,
'price': 3.5
}
-
fruit_info ['price'] = 1.5
-
my_list [3.5] = 1.5
-
1.5 = fruit_info ['price]
-
my_list['price'] == 1.5
What value would be returned by this check for equality?
Q41.5 != 6
-
yes
-
False
-
True
-
None
Explanation: In Python, !=
is equivalent to not equal to.
What does a class’s __init__()
method do?
Q42. - It makes classes aware of each other if more than one class is defined in a single code file.
- It is included to preserve backward compatibility from Python 3 to Python 2, but it no longer needs to be used in Python 3.
- It is a method that acts as a constructor and is called automatically whenever a new object is created from a class. It sets the initial state of a new object.
- It initializes any imports you may have included at the top of your file.
Voorbeeld:
class test:
def __init__(self):
print('I came here without your permission lol')
pass
t1 = test()
>>> 'I came here without your permission lol'
What is meant by the phrase “space complexity”?
Q43.-
How many microprocessors it would take to run your code in less than one second
-
How many lines of code are in your code file
-
The amount of space taken up in memory as a function of the input size
-
How many copies of the code file could fit in 1 GB of memory
What is the correct syntax for creating a variable that is bound to a dictionary?
Q44.-
fruit_info = {'fruit': 'apple', 'count': 2, 'price': 3.5}
-
fruit_info =('fruit': 'apple', 'count': 2,'price': 3.5 ).dict()
-
fruit_info = ['fruit': 'apple', 'count': 2,'price': 3.5 ].dict()
-
fruit_info = to_dict('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?
Q45.fruits = {'Apples': 5, 'Oranges': 3, 'Bananas': 4}
-
fruit_names = [x in fruits.keys() for x]
-
fruit_names = for x in fruits.keys() *
-
fruit_names = [x for x in fruits.keys()]
-
fruit_names = x for x in fruits.keys()
self
keyword when defining or calling methods on an instance of an object?
Q46. Wat is het doel van de -
self
refers to the class that was inherited from to create the object usingself
. - There is no real purpose for the
self
methode. It’s just legacy computer science jargon that Python keeps to stay consistent with other programming languages. -
self
means that no other arguments are required to be passed into the method. -
self
refers to the instance whose method was called.
Explanation: – Try running the example of the Q42 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 it hasn’t been specified, which is the instance itself.
What statement about the class methods is true?
Q47.- 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 it 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.
Referentie
Class methods are methods that are called on the class itself, not on a specific object instance. daarom, it belongs to a class level, and all class instances share a class method.
What does it mean for a function to have linear runtime?
Q48.- You did not use very many advanced computer programming concepts in your code.
- The difficulty level your code is written at is not that high.
- It will take your program less than half a second to run.
- 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?
Q49.-
def getMaxNum(list_of_nums): # body of function goes here
-
func get_max_num(list_of_nums): # body of function goes here
-
func getMaxNum(list_of_nums): # body of function goes here
-
def get_max_num(list_of_nums): # body of function goes here
The use of underscores as word separators dates back to the late 1960s. It is particularly associated with C, is found in The C Programming Language (1978), and contrasted with the Pascal case (a type of camel case). Echter, the convention traditionally had no specific name: the Python programming language style guide refers to it simply as “lagercase_with_underscores”.[2] Within Usenet the term snake_case was first seen in the Rubycommunity in 2004,[3] used by Gavin Kistner, schrift: BTW…what _do you call that naming style? snake_case? That’s what I’ll call it until someone corrects me.
According to the PEP 8 coding style guidelines, how should constant values be named in Python?
Q50.- in camel case without using underscores to separate words — bv.
maxValue = 255
- in lowercase with underscores to separate words — bv.
max_value = 255
- in all caps with underscores separating words — bv.
MAX_VALUE = 255
- in the mixed case without using underscores to separate words — bv.
MaxValue = 255
Use an uppercase single letter, word, of woorden. Scheid woorden met onderstrepingstekens om de leesbaarheid te verbeteren. Referentie
Q51. Beschrijf de functionaliteit van een deque.
- Een deque voegt items toe aan de ene kant en verwijdert items aan de andere kant.
- Een deque voegt items toe aan een of beide zijden, maar verwijdert alleen items van de bovenkant.
- Een deque voegt items toe aan een of beide uiteinden en verwijdert items aan een of beide uiteinden.
- Een deque voegt alleen items toe aan de bovenkant, maar verwijdert ze van een of beide kanten.
Deque of Double Ended Queue is een algemene versie van de Queue-gegevensstructuur waarmee invoeging en verwijdering aan beide uiteinden mogelijk is. referentie
Q52. Wat is de juiste syntaxis voor het maken van een variabele die aan een set is gebonden??
-
my_set = {0, 'apple', 3.5}
-
my_set = to_set(0, 'apple', 3.5)
-
my_set = (0, 'apple', 3.5).to_set()
-
my_set = (0, 'apple', 3.5).set()
__init__()
methode die geen parameters gebruikt?
Q53. Wat is de juiste syntaxis voor het definiëren van een - :
class __init__(self):
pass
- :
def __init__():
pass
- :
class __init__():
pass
- :
def __init__(self):
pass
Q54. Welke van de volgende beweringen is WAAR over hoe numerieke gegevens zouden worden georganiseerd in een binaire zoekboom?
- Voor elk gegeven knooppunt in een binaire zoekboom, de waarde van het knooppunt is groter dan alle waarden in de linker subboom van het knooppunt en kleiner dan die in de rechter subboom.
- Binaire zoekboom kan niet worden gebruikt om numerieke gegevens te ordenen en te doorzoeken, gezien de complicaties die optreden bij zeer diepe bomen.
- Het bovenste knooppunt van de binaire zoekboom zou een willekeurig getal zijn. Alle knooppunten links van het bovenste knooppunt moeten kleiner zijn dan het nummer van het bovenste knooppunt, maar ze hoeven niet op een bepaalde manier te worden besteld.
- De kleinste numerieke waarde zou in het bovenste knooppunt terechtkomen. Het volgende hoogste getal zou in het linker kindknooppunt terechtkomen, het volgende hoogste getal daarna zou in het rechter kindknooppunt terechtkomen. Dit patroon zou zich voortzetten totdat alle numerieke waarden zich in hun knooppunt bevonden.
In de informatica, een binaire zoekboom (BST), ook wel een geordende of gesorteerde binaire boom genoemd, is een gewortelde binaire boomdatastructuur waarbij de sleutel van elk intern knooppunt groter is dan alle sleutels in de linkersubboom van het betreffende knooppunt en kleiner dan die in de rechtersubboom. referentie
Q55. Waarom zou je een decorateur gebruiken??
- Een decorateur is vergelijkbaar met een klasse en moet worden gebruikt als u functioneel programmeert in plaats van objectgeoriënteerd programmeren.
- Een decorateur is een visuele indicatie voor iemand die uw code leest dat een deel van uw code cruciaal is en niet mag worden gewijzigd.
- You use the decorator to alter the functionality of a function without having to modify the function code.
- An import statement is preceded by a decorator, python knows to import the most recent version of whatever package or library is being imported.
Decorators allow us to wrap another function to extend the behavior of the wrapped function, without permanently modifying it. referentie
When would you use a for loop?
Q56.- Only in some situations, as loops are used only for certain types of programming.
- When you need to check every element in an iterable of known length.
- When you want to minimize the use of strings in your code.
- When you want to run code in one file for a function in another file.
What is the most self-descriptive way to define a function that calculates sales tax on a purchase?
Q57.- EEN:
def tax(my_float):
''' 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.'''
pass
- B:
def tx(amt):
''' Gets the tax on an amount.'''
- C:
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.'''
- D:
def calculate_sales_tax(subtotal):
pass
What would happen if you did not alter the state of the element that an algorithm is operating on recursively?
Q58.- You do not have to alter the state of the element the algorithm is recursing on.
- You would eventually get a KeyError when the recursive portion of the code ran out of items to recurse on.
- You would get a RuntimeError: maximum recursion depth exceeded.
- The function using recursion would return None.
What is the runtime complexity of searching for an item in a binary search tree?
Q59.- The runtime for searching in a binary search tree is O(1) because each node acts as a key, similar to a dictionary.
- The runtime for searching in a binary search tree is O(N!) because every node must be compared to every other node.
- The runtime for searching in a binary search tree is generally O(de verbinding), where h is the height of the tree.
- The runtime for searching in a binary search tree is O(N) because every node in the tree must be visited.
Why would you use mixin
?
Q60. - You use a
mixin
to force a function to accept an argument at runtime even if the argument wasn’t included in the function’s definition. - You use a
mixin
to allow a decorator to accept keyword arguments. - You use a
mixin
to make sure that a class’s attributes and methods don’t interfere with global variables and functions. - If you have many classes that all need to have the same functionality, you’d use a
mixin
to define that functionality.
There are two main situations where mixins are used: You want to provide a lot of optional features for a class. You want to use one particular feature in a lot of different classes. referentie explanation
What is the runtime complexity of adding an item to a stack and removing an item from a stack?
Q61.- Add items to a stack in O(1) time and remove items from a stack on O(N) tijd.
- Add items to a stack in O(1) time and remove items from a stack in O(1) tijd.
- Add items to a stack in O(N) time and remove items from a stack on O(1) tijd.
- Add items to a stack in O(N) time and remove items from a stack in O(N) tijd.
Which statement accurately describes how items are added to and removed from a stack?
Q62.- a stack adds items to one side and removes items from the other side.
- a stack adds items to the top and removes items from the top.
- a stack adds items to the top and removes items from anywhere in the stack.
- a stack adds items to either end and removes items from either end.
Explanation: Stack uses the last in first out nadering.
What is a base case in a recursive function?
Q63.- 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.
- The base case is a summary of the overall problem that needs to be solved.
- The base case is passed in as an argument to a function whose body makes use of recursion.
- The base case is similar to a base class, in that it can be inherited by another object.
Why is it considered good practice to open a file from within a Python script by using the with
trefwoord?
Q64. - De
with
keyword lets you choose which application to open the file in. - De
with
keyword acts like afor
loop, and lets you access each line in the file one by one. - There is no benefit to using the
with
keyword for opening a file in Python. - 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.
It is good practice to use the ‘with’ keyword when dealing with file objects. The advantage is that the file is properly closed after its suite finishes, even if an exception is raised at some point. Using with is also much shorter than writing equivalent try-finally blocks:
voorbeeld
>>> f = open('workfile', 'w', encoding="utf-8")
>>> with open('workfile', encoding="utf-8") as f:
read_data = f.read()
# We can check that the file has been automatically closed.
>>> f.closed
True
Why would you use a virtual environment?
Q65.- Virtual environments create a “bubble” around your project so that any libraries or packages you install within it don’t affect your entire machine.
- Teams with remote employees use virtual environments so they can share code, do code reviews, and collaborate remotely.
- Virtual environments were common in Python 2 because they augmented missing features in the language. Virtual environments are not necessary in Python 3 due to advancements in the language.
- Virtual environments are tied to your GitHub or Bitbucket account, allowing you to access any of your repos virtually from any machine.
What is the correct way to run all the doctests in a given file from the command line?
Q66.-
python3 -m doctest <_filename_>
-
python3 <_filename_>
-
python3 <_filename_> rundoctests
-
python3 doctest
There is also a command line shortcut for running testmod(). You can instruct the Python interpreter to run the doctest module directly from the standard library and pass the module name(s) on the command line: python -m doctest -v example.py
This will import example.py as a standalone module and run testmod() ben ermee bezig. Note that this may not work correctly if the file is part of a package and imports other submodules from that package.
referentie
tutorial video
What is a lambda function ?
Q67.- any function that makes use of scientific or mathematical constants, often represented by Greek letters in academic writing
- a function that gets executed when decorators are used
- any function whose definition is contained within five lines of code or fewer
- a small, anonymous function that can take any number of arguments but has only expression to evaluate
Explanation:
The lambda notation is an anonymous function that can take any number of arguments with only a single expression (d.w.z., 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.
What is the primary difference between lists and tuples?
Q68.- You can access a specific element in a list by indexing to its position, but you cannot access a specific element in a tuple unless you iterate through the tuple
- 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.
- 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 change the data that is inside them at any time.
- Lists can hold several data types inside them at once, but tuples can only hold the same data type if multiple elements are present.
What does a generator return?
Q69.- Geen
- An iterable object
- A linked list data structure from a non-empty list
- All the keys of the given dictionary
What is the difference between class attributes and instance attributes?
Q70.- Instance attributes can be changed, but class attributes cannot be changed
- Class attributes are shared by all instances of the class. Instance attributes may be unique to just that instance
- There is no difference between class attributes and instance attributes
- Class attributes belong just to the class, not to the instance of that class. Instance attributes are shared among all instances of a class
What is the correct syntax for creating an instance method?
Q71.- :
def get_next_card():
# method body goes here
- :
def get_next_card(self):
# method body goes here
- :
def self.get_next_card():
# method body goes here
- :
def self.get_next_card(self):
# method body goes here
What is the correct way to call a function?
Q72.-
get_max_num([57, 99, 31, 18])
-
call.(get_max_num)
-
def get_max_num([57, 99, 31, 18])
-
call.get_max_num([57, 99, 31, 18])
How do you add a comment to an existing Python script?
Q73.-
-- This is a comment
-
# This is a comment
-
/* This is a comment */
-
// This is a comment
What is the correct syntax for replacing the string apple
in the list with the string orange
?
Q74. my_list = ['kiwi', 'apple', 'banana']
-
orange = my_list[1]
-
my_list[1] = 'orange'
-
my_list['orange'] = 1
-
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?
Q75.- Nothing will happen; your computer knows when to stop running the code in the while loop.
- You will get a KeyError.
- Your code will get stuck in an infinite loop.
- You will get a WhileLoopError.
Describe the functionality of a queue.
Q76.- A queue adds items to either end and removes items from either end.
- A queue adds items to the top and removes items from the top.
- A queue adds items to the top and removes items from anywhere in, a list.
- A queue adds items to the top and removes items from anywhere in the queue.
Which choice is the most syntactically correct example of conditional branching?
Q77.- EEN:
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.")
- B:
num_people = 5
if num_people > 10:
print("There is a lot of people in the pool.")
if num_people > 4:
print("There are some people in the pool.")
else:
print("There is no one in the pool.")
- C:
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.")
- D:
if num_people > 10;
print("There is a lot of people in the pool.")
if num_people > 4;
print("There are some people in the pool.")
else;
print("There is no one in the pool.")
How does defaultdict
werk?
Q78. -
defaultdict
will automatically create a dictionary for you that has keys which are the integers 0-10. -
defaultdict
forces a dictionary to only accept keys that are of the types specified when you created thedefaultdict
(such as strings or integers). - 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 aKeyError
. -
defaultdict
stores a copy of a dictionary in memory that you can default to if the original gets unintentionally modified.
defaultdict
is a container-like dictionary present in the module collections. The functionality of both dictionaries and defaultdict
are almost the same except for the fact that defaultdict
never raises a KeyError
. It provides a default value for the key that does not exist.
voorbeeld
# Function to return a default
# values for keys that are not
# present
def def_value():
return "Not Present"
# Defining the dict
d = defaultdict(def_value)
What is the correct syntax for adding a key called variety
naar de fruit_info
dictionary that has a value of Red Delicious
?
Q79. -
fruit_info['variety'] == 'Red Delicious'
-
fruit_info['variety'] = 'Red Delicious'
-
red_delicious = fruit_info['variety']
-
red_delicious == fruit_info['variety']
When would you use a while
loop?
Q80. - 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 running.
- When you want some code to continue running as long as some condition is true.
- When you need to run two or more chunks of code at once within the same file.
Simple Example
i = 1
while i<6:
print('Countdown:',i)
i = i + 1
__init__()
method that sets instance-specific attributes upon creation of a new class instance?
Q81. Wat is de juiste syntaxis voor het definiëren van een - :
def __init__(self, attr1, attr2):
attr1 = attr1
attr2 = attr2
- :
def __init__(attr1, attr2):
attr1 = attr1
attr2 = attr2
- :
def __init__(self, attr1, attr2):
self.attr1 = attr1
self.attr2 = attr2
- :
def __init__(attr1, attr2):
self.attr1 = attr1
self.attr2 = attr2
Explanation:: When instantiating a new object from a given class, de __init__()
method will take both attr1
en attr2
, and set its values to their corresponding object attribute, that’s why the need of using self.attr1 = attr1
Een andere populaire toetsenbordmodifier is de Alt-toets die kan worden gebruikt voor het uitvoeren van verschillende taken waarvoor meerdere stappen nodig zijn, zoals knippen attr1 = attr1
.
What would this recursive function print if it is called with no parameters?
Q82.def count_recursive(n=1):
if n > 3:
return
print(n)
count_recursive(n + 1)
- :
1
1
2
2
3
3
- :
3
2
1
- :
3
3
2
2
1
1
- :
1
2
3
In Python, when using sets, je gebruikt _ to calculate the intersection between two sets and _ to calculate the union.
Q83.-
Intersect
;union
-
|
;&
-
&
;|
-
&&
;||
What will this code fragment return?
Q84.import numpy as np
np.ones([1,2,3,4,5])
- It returns a 5×5 Matrix; each row will have the values 1,2,3,4,5.
- It returns an array with the values 1,2,3,4,5.
- It returns five different square matrices filled with ones. The first is 1×1, the second 2×2, and so on to 5×5.
- It returns a 5-dimensional array of size 1x2x3x4x5 filled with 1s.
You encounter a FileNotFoundException while using just the filename in the open
functie. What might be the easiest solution?
Q85. - Make sure the file is on the system
PATH
. - Create a symbolic link to allow better access to the file.
- Copy the file to the same directory as where the script is running from.
- Add the path to the file to the
PYTHONPATH
environment variable.
Q86. wat zal dit commando opleveren?
{x for x in range(100) if x%3 == 0}
- Een verzameling van alle veelvouden van 3 minder dan 100.
- Een verzameling van alle getallen uit 0 naar 100 vermenigvuldigd met 3.
- Een lijst met alle veelvouden van 3 minder dan 100.
- Een verzameling van alle veelvouden van 3 minder dan 100 exclusief 0.
referentie Het is een Set Comprehension
omdat in ‘{}’, gekrulde haakjes, dus het zal een 'Set' retourneren!
Q87. Wat doet de // operator in Python 3 laat je doen?
- Voer een gehele deling uit.
- Voer bewerkingen uit op exponenten.
- Zoek de rest van een delingsoperatie.
- Voer een drijvende-kommaverdeling uit.
Q88. Welk bestand wordt geïmporteerd om datums in Python te gebruiken?
-
datetime
-
dateday
-
daytime
-
timedate
What is the correct syntax for defining a class called Game?
Q89.-
def Game(): pass
-
def Game: pass
-
class Game: pass
-
class Game(): pass
What is the correct syntax for calling an instance method on a class named Game?
Q90.-
my_game = Game(self) self.my_game.roll_dice()
-
my_game = Game() self.my_game.roll_dice()
-
my_game = Game() my_game.roll_dice()
-
my_game = Game(self) my_game.roll_dice(self)
Q91. Wat is de output van deze code? (NumPy is geïmporteerd als np.)?
a = np.array([1,2,3,4])
print(a[[False, True, False, False]])
-
{0,2}
-
[2]
-
{2}
-
[0,2,0,0]
Q92. Stel dat u een stringvariabele hebt die is gedefinieerd als y=”spullen;ding;rommel;”. Wat zou de output van deze code zijn?
z = y.split(';')
len(z)
- 17
- 4
- 0
- 3
Explanation::
y="stuff;thing;junk"
len(z) ==> 3
y="stuff;thing;junk;"
len(z) ==> 4
Q93. Wat is de output van deze code?
num_list = [1,2,3,4,5]
num_list.remove(2)
print(num_list)
-
[1,2,4,5]
-
[1,3,4,5]
-
[3,4,5]
-
[1,2,3]
Explanation:: .remove()
is gebaseerd op de waarde van het artikel, niet de index; hier, het verwijdert het overeenkomende item “2”. Als u een item wilt verwijderen op basis van de index, jij zou gebruiken .pop()
.
num_list = [1,2,3,4,5]
num_list.pop(2)
>>> [1,2,4,5]
num_list.remove(2)
>>> [1,3,4,5]
Q94. Met welk commando wordt een lijst gemaakt 10 naar beneden 1? Voorbeeld:
[10,9,8,7,6,5,4,3,2,1]
-
reversed(list(range(1,11)))
-
list(reversed(range(1,10)))
-
list(range(10,1,-1))
-
list(reversed(range(1,11)))
Which fragment of code will print the same output as this fragment?
Q95.import math
print(math.pow(2,10)) # prints 2 elevated to the 10th power
- :
print(2^10)
- :
print(2**10)
- :
y = [x*2 for x in range(1,10)]
print(y)
- :
y = 1
for i in range(1,10):
y = y * 2
print(y)
Elements surrounded by []
zijn _, {}
zijn _, en ()
zijn _.
Q96. - sets only; lists or dictionaries; tuples
- lists; sets only; tuples
- tuples; sets or lists; deze cursus in elektronische steno kost je slechts een paar uur studie en oefening om vertrouwd te raken met het systeem
- lists; dictionaries or sets; tuples
Q97. Wat is de output van deze code? (NumPy is geïmporteerd als np.)
table = np.array([
[1,3],
[2,4]])
print(table.max(axis=1))
-
[2, 4]
-
[3, 4]
-
[4]
-
[1,2]
What will this code print?
Q98.number = 3
print (f"The number is {number}")
-
The number is 3
-
the number is 3
-
THE NUMBER IS 3
- It throws a
TypeError
because the integer must be cast to a string.
Which syntax correctly creates a variable that is bound to a tuple?
Q99.-
my_tuple tup(2, 'apple', 3.5) %D
-
my_tuple [2, 'apple', 3.5].tuple() %D
-
my_tuple = (2, 'apple', 3.5)
-
my_tuple = [2, 'apple', 3.5]
Which mode is not a valid way to access a file from within a Python script?
Q100.-
write('w')
-
scan('s')
-
append('a')
-
read('r')
NumPy allows you to multiply two arrays without a for loop. This is an example of _.
Q101.- Vectorization.
- Attributions.
- Acceleration.
- Functional programming.
What built-in Python data type can be used as a hash table?
Q102.-
set
-
list
-
tuple
-
dictionary
Which Python function allows you to execute Linux shell commands in Python?
Q103.-
sys.exc_info()
-
os.system()
-
os.getcwd()
-
sys.executable
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?
Q104.my_dictionary = {
'A': 1,
'B': 2,
'C': 3,
'D': 4,
'E': 5
}
letters = []
for letter in my_dictionary.values():
letters.append(letter)
-
letters = my_dictionary.keys()
-
letters = [letter for (letter, number) in my_dictionary.items()]
-
letters4 = list(my_dictionary)
Explanation: The first one (the correct option) returns the list of the values (the numbers). The rest of the options return a list of the keys.
When an array is large, NumPy will not print the entire array when given the built-in print
functie. What function can you use within NumPy to force it to print the entire array?
Q105. -
set_printparams
-
set_printoptions
-
set_fullprint
-
setp_printwhole
When would you use a try/except block in code?
Q106.- You use
try/except
blocks when you want to run some code, but 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 tests will always pass. - 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 what they were looking for, they can leave comments under theexcept
trefwoord. - You use
try/except
blocks so that none of your functions or methods returnNone
.
In Python, how can the compiler identify the inner block of a for loop?
Q107.-
because of the level of indentation after the for loop
-
because of the end keyword at the end of the for loop
-
because the block is surrounded by brackets ({})
-
because of the blank space at the end of the body of the for loop
What Python mechanism is best suited for telling a user they are using a deprecated function
Q108.-
sys.stdout
- Traceback
- Warnings
- Exceptions
What will be the value of x
after running this code?
Q109. x = {1,2,3,4,5}
x.add(5)
x.add(6)
-
{1, 2, 3, 4, 5, 5, 6}
-
{5, 6, 1, 2, 3, 4, 5, 6}
-
{6, 1, 2, 3, 4, 5}
-
{1, 2, 3, 4, 5, 6}
Explanation: De .add()
method adds the element to the set only if it doesn’t exist.
How would you access and store all of the keys in this dictionary at once?
Q110.fruit_info = {
'fruit': 'apple',
'count': 2,
'price': 3.5
}
-
my_keys = fruit_info.to_keys()
-
my_keys = fruit_info.all_keys()
-
my_keys = fruit_info.keys
-
my_keys = fruit_info.keys()
What is wrong with this function definition?
Q111.def be_friendly(greet = "How are you!", name):
pass
-
name
is a reserved word. - Underscores are not allowed in function names.
- A non-default argument follows a default argument.
- There is nothing wrong with this function definition.
Given that NumPy is imported as np
, which choice will return True
?
Q112. - :
a = np.zeros([3,4])
b = a.copy()
np.array_equal(a,b)
- :
a = np.empty([3,4])
b = np.empty([3,4])
np.array_equal(a,b)
- :
a = np.zeros([3,4])
b = np.zeros([4,3])
np.array_equal(a,b)
- :
a = np.array([1, np.nan])
np.array_equal(a,a)
How do you add a comment to an existing Python script?
Q113.-
// This is a comment
-
# This is a comment
-
-- This is a comment
-
/* This is a comment *\
In this code fragment, what will the values of c and d be equivalent to?
Q114.import numpy as np
a = np.array([1,2,3])
b = np.array([4,5,6])
c = a*b
d = np.dot(a,b)
- EEN
c = [ a[1] * b[1], a[2] * b[2], a[3] * b[3] ]
d = sum(c)
- B
c = a[0] * b[0], a[1] * b[1], a[2] * b[2]
d = [ a[0] * b[0], a[1] * b[1], a[2] * b[2] ]
- C
c = [ a[0] * b[0], a[1] * b[1], a[2] * b[2] ]
d = sum(a) + sum(b)
- D
c = [ a[0] * b[0], a[1] * b[1], a[2] * b[2] ]
d = sum(c)
What two functions within the NumPy library could you use to solve a system of linear equations?
Q115.-
linalg.eig() and .matmul()
-
linalg.inv() and .dot()
-
linalg.det() and .dot()
-
linalg.inv() and .eye()
Explanation: Understanding this answer requires knowledge of linear algebra. Some systems of equations can be solved by the method of diagonalization, which involves finding the eigenvectors and eigenvalues of the system’s matrix and multiplying related matrices.
What is the correct syntax for creating a variable that is bound to a list?
Q116.-
my_list = (2, 'apple', 3.5)
-
my_list = [2, 'apple', 3.5]
-
my_list = [2, 'apple', 3.5].to_list()
-
my_list = to_list(2, 'apple', 3.5)
This code provides the _ of the list of numbers.
Q117.num_list = [21, 13, 19, 3, 11, 5, 18]
num_list.sort()
num_list[len(num_list) // 2]
- modus
- gemiddelde
- gemiddelde
- mediaan-
Explanation: //
is the operator for floor division, which is a normal 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, which is the value separating the higher half from the lower half of a data sample, by finding the index of the list item in the middle of the list. (This is sufficient for a list with an odd number of items; if the list had an even number of items, you would average the values of the two middle items to find the median value.)
What are the two main data structures in the Pandas library?
Q118.- Arrays and DataFrames
- Series and Matrixes
- Matrixes and DataFrames
- Series and DataFrames
Suppose you have a variable named vector
of type np.array with 10,000 elementen. How can you turn vector
into a variable named matrix
with dimensions 100×100?
Q119. -
matrix = (vector.shape = (100,100))
-
matrix = vector.to_matrix(100,100)
-
matrix = matrix(vector,100,100)
-
matrix = vector.reshape(100, 100)
Which choice is an immutable data type?
Q120.- Woordenboek
- Lijst
- Set
- String
Q121. Wat is de output van deze code?
def myFunction(country = "France"):
print("Hello, I am from", country)
myFunction("Spain")
myFunction("")
myFunction()
- :
Hello, I am from Spain
Hello, I am from
Hello, I am from
- :
Hello, I am from France
Hello, I am from France
Hello, I am from France
- :
Hello, I am from Spain
Hello, I am from
Hello, I am from France
- :
Hello, I am from Spain
Hello, I am from France
Hello, I am from France
Choose the option below for which instance of the class cannot be created.
Q122.- Anonymous Class
- Parent Class
- Nested Class
- Abstract Class
Using Pandas, we load a data set from Kaggle, as structured in the image below. Which command will return the total number of survivors?
Q123.-
sum(titanic['Survived'])
-
[x for x in titanic['Survived'] if x == 1]
-
len(titanic["Survived"])
-
sum(titanic['Survived']==0)
Explanation: De titanic['Survived']
returns a pandas.Series
voorwerp, which contains the Survived
column of the DataFrame
. Adding the values of this column (d.w.z.. sum(titanic['Survived'])
) returns the total number of survivors since a survivor is represented by a 1 and a loss by 0.
How would you create a list of tuples matching these lists of characters and actors?
Q124.characters = ["Iron Man", "Spider Man", "Captain America"]
actors = ["Downey", "Holland", "Evans"]
# example output : [("IronMan", "Downey"), ("Spider Man", "Holland"), ("Captain America", "Evans")]
-
[(x,y)] for x in characters for y in actors]
-
zip(characters, actors)
-
d = {} for x in range(1, len(characters)): d[x] = actors[x]
-
{x:y for x in characters for y in actors}
What will this statement return?
Q125.{x : x*x for x in range(1,100)}
- A dictionary with
x
as a key, enx
squared as its value; van 1 naar 100. - A dictionary with
x
as a key, enx
squared as its value; van 1 naar 99. - A set of tuples, bestaande uit (
x
,x
squared); van 1 naar 99. - A list with all numbers squared from 1 naar 99.
Jaccard Similarity is a formula that tells you how similar two sets are. It is defined as the cardinality of the intersection divided by the cardinality of the union. Which choice is an accurate implementation in Python?
Q126.-
def jaccard(a, b): return len (a | b) / len (a & b)
-
def jaccard(a, b): return len (a & b) / len (a | b)
-
def jaccard(a, b): return len (a && b) / len (a || b)
-
def jaccard(a, b): return a.intersection(b) / a.union(b)
Which choice is not a native numerical type in Python?
Q127.- Long
- Int
- Float
- Double
What will be the output of this code?
Q128.[1,2,3] * 3
-
[3,2,3]
-
[1, 2, 3, 1, 2, 3, 1, 2, 3]
- You will get a type error.
-
[3,6,9]
Given a list defined as numbers = [1,2,3,4]
, what is the value of numbers[-2]
?
Q129. - 1
- 3
- 2
- An IndexError exception is thrown.
Which statement about strings in Python is true?
Q130.- Strings can be enclosed by double quotes (“) or single quotes (‘).
- Strings can only be enclosed in single quotes (‘).
- Single character strings must be enclosed in single quotes (‘), and the rest must be enclosed in double quotes (“).
- Strings can only be enclosed in double quotes (“).
_init_()
methode die geen parameters gebruikt?
Q131. Wat is de juiste syntaxis voor het definiëren van een -
def*init*(self): pass
-
class*init*(self): pass
-
class*init*(): pass
-
def*init*(): pass
()
– empty parameter. self
– refers to all instances within a class. _init_
– a reserved method, AKA a constructor. _init_()
– always executed when the class is being initiated.
Suppose you need to use the sin
function from the math
bibliotheek. What is the correct syntax for importing only that function?
Q132. -
using math.sin
-
import math.sin
-
from math import sin
-
import sin from math
Explanation: De from..import
statement allows you to import specific functions/variables from a module instead of importing everything.
What do you get if you apply numpy.sum() to a list that contains only Boolean values?
Q133.-
0
-
the count of all True values
-
a type error
-
None
What will this code print?
Q134.print ("foo" if (256).bit_length() > 8 else "bar")
-
True
-
foo
- You will get an error message because constant integer values are not classes.
-
bar
If you do not explicitly return a value from a function, wat gebeurt er?
Q135.- If the return keyword is absent, the function will return
True
. - The function will enter an infinite loop because it will not know when to stop executing its code.
- The function will return a
RuntimeError
if you do not return a value. - If the return keyword is absent the function will return
None
.
It is often the case that the pandas library is used for _ data and NumPy for _ gegevens.
Q136.- string; numerical
- unstructured; structured
- numerical; tabular
- tabular; numerical
- Explanation: The Pandas library is commonly used for working with tabular data, such as data in the form of tables or spreadsheets. It provides data structures and functions for data manipulation and analysis. Anderzijds, NumPy is a powerful library for numerical computing in Python, and it is often used for performing mathematical operations on numerical data, such as arrays and matrices.
What do you need to do to install additional packages into Python?
Q137.- Use a C compiler like
gcc
ofclang
. - Use a package manager like
pip
ofconda
. - Use an IDE like Notepad++ or Idle.
- Use a package manager like NPM or NuGet.
The image below was created using Matplotlib. It is a distribution plot of a list of integers filled with numbers using the function _ and plotted with _.
Q138.-
random.uniform(0,50);plt.hist
-
random.gauss(50,20);plt.hist
-
random();plt.scatter
-
random.triangular(0,50);plt.bar
In this code fragment, what will be the values of a
en b
?
Q139. import numpy as np
a = np.arange(100)
b = a[50:60:2]
-
a
: all integers from 0 naar 99 (inclusief);b
: all even integers from 50 naar 58 (inclusief). -
a
: all integers from 0 naar 100 (inclusief);b
: all even integers from 50 naar 60 (inclusief). -
a
: all integers from 0 naar 99 (inclusief);b
: all even integers from 50 naar 60 (inclusief). -
a
: all integers from 0 naar 99 (inclusief);b
: all odd integers from 49 naar 59 (inclusief).
When using NumPy in Python, how do you check the dimensionality (number and length of dimensions) of an object called my_object
?
Q140. -
my_object.get_shape()
-
my_object.shape
-
my_object.dim()
-
len(my_object)
Assume you have a non-empty list named mylist
and you want to search for a specific value. The minimum number of comparisons will be __ and the maximum number of comparisons will be _?
Q141. -
len(mylist); len(mylist)
-
1; len(mylist)
-
2; len(mylist)
-
0; len(mylist)
Explanation: Can use a break statement and the value being searched can be the first element of the list, given that it is non-empty.
If a function does not have a return statement, what does it return?
Q142.-
0
-
True
-
None
-
False
Q143. Suppose you want to double-check if two matrices can be multiplied using NumPy for debugging purposes. How would you complete this code fragment by filling in the blanks with the appropriate variables?
import numpy as np
def can_matrices_be_multiplied (matrix1, matrix2):
rowsMat1, columnsMat1 = matrix1.shape
rowsMat2, columnsMat2 = matrix2.shape
if _____ == ______ :
print('The matrices can be multiplied!')
return True
else:
return False
- columnsMat1; rowsMat1;
- columnsMat1; rowsMat2;
- columnsMat1; columnsMat2;
- columnsMat2; rowsMat1;
referentie. A matrix can be multiplied by any other matrix that has the same number of rows as the first columns. I.E. A matrix with 2 columns can be multiplied by any matrix with 2 rijen
Q144. What is the output of this comprehension?
[(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)]
- [(1, 2), (2, 3), (3, 4), (4, 5)]
Q145. In Python, a class method must have __ as a function decorator, en de eerste parameter van de methode zal een verwijzing zijn naar __.
- @klasmethode; de klas
- inline; de klas
- statisch; self
- @statisch; self
Q146. Welk codefragment wordt afgedrukt Mijn naam is Joffrey, zoon van Robert?
- :
class Father():
name = 'Robert'
class Person(Father):
def __init__(self, name):
self.fathername = super.name
self.name = name
def introduce(self):
print("My name is", self.name, "son of", self.fathername)
king = Person("Joffrey")
king.introduce()
- :
class Father():
name = 'Robert'
class Person(Father):
def __init__(self, name):
self.fathername = self.name
self.name = name
def introduce(self):
print("My name is", self.name, "son of", self.fathername)
king = Person("Joffrey")
king.introduce()
- :
class Father():
name = 'Robert'
class Person(Father):
def __init__(self, name):
self.name = name
def introduce(self):
print("My name is", self.name, "son of", super.name)
king = Person("Joffrey")
king.introduce()
- :
class Father():
name = 'Robert'
class Person(Father):
def __init__(self, name):
self.name = name
def introduce(self):
print("My name is", self.name, "son of", base.name)
king = Person("Joffrey")
king.introduce()
Explanation: In de eerste, super heeft het niet .name
(zou moeten zijn self.name
). De derde laat Robert vallen, en base
wordt niet gedefinieerd in de 4e.
Q147. Wat levert deze code op in de console, ervan uitgaande dat het standaarddictaat al is geïmporteerd?
animals = {
'a': ['ant', 'antelope', 'armadillo'],
'b': ['beetle', 'bear', 'bat'],
'c': ['cat', 'cougar', 'camel']
}
animals = defaultdict(list, animals)
print(animals['b'])
print(animals['d'])
- EEN
['beetle', 'bear', 'bat']
[]
- B
['beetle', 'bear', 'bat']
# an exception will be thrown
- C
['beetle', 'bear', 'bat']
None
- D
['bat', 'bear', 'beetle']
[]
Explanation: Woordenboeken resulteren meestal in een uitzondering bij het gebruik van de syntaxis van vierkante haakjes. Defaultdict retourneert hier een standaardwaarde die is toegewezen door de eerste parameter, dus in plaats van een uitzondering te genereren, ze retourneren de standaardwaarde. Houd er rekening mee dat dit als volgt moet worden geïmporteerd: from collections import defaultdict
n
is al gedefinieerd als een positief geheel getal.)
Q148. Wat zal deze regel code retourneren? (Aannemen [x*2 for x in range(1,n)]
- Een lijst met alle even getallen kleiner dan 2*n.
- Een woordenboek met alle even getallen kleiner dan 2*n.
- Een lijst met alle oneven getallen kleiner dan 2*n.
- Een lijst met alle even getallen kleiner dan of gelijk aan 2*n.
Q149. Wat drukt deze code af in de console?
x = 18
if x > 10:
if x > 15:
print('A')
else:
print('B')
else:
print('C')
- C
- EEN B
- B
- EEN
Q150. Wat is de maximale lengte van een Python-identifier?
- 32
- 16
- 128
- Er is geen vaste lengte opgegeven.
referentie Nee Er is geen vaste lengte gespecificeerd, maar Pep-8 specificeert onder “Maximale lijnlengte” naar “Beperk alle regels tot een maximum van 79 karakters”.
i
variabele zijn wanneer de volgende lus zijn uitvoering beëindigt?
Q151. Wat zal de waarde zijn van de for i in range(5): pass
- 5
- De variabele wordt niet meer beschikbaar.
- 6
- 4
f-strings
worden ook wel genoemd:
Q152. - Opgemaakte tekenreeksexpressies.
- Functionele snaren.
- Modulo-geformatteerde strings.
- Geformatteerde letterlijke tekenreeksen.
Q153. Hoeveel CPU's (of kernen) zal de Python-threading-bibliotheek tegelijkertijd profiteren?
- een.
- Alle beschikbare CPU's.
- Twee.
- Drie.
Explanation:: Python threading is restricted to a single CPU at one time. The multiprocessing library will allow you to run code on different processors.
Q154. What will be the value of y
in this code?
x = 5
y = 1 + (20 if x < 5 else 30)
-
False
-
21
-
2
-
31
Explanation: If you have only one statement to execute, one for if
and one for else
, you can put it all on the same line.
x = 5
# This is the same statement expanded to multiple lines
y = 1
if (x < 5):
y += 20
else:
y += 30
Q155.The process of pickling in Python includes?
- Conversion of a Python object hierarchy into byte stream.
- Conversion of a data table into a list.
- Conversion of a byte stream into Python object hierarchy.
- Conversion of a list into a data table.
referentie
“Pickling” is the process whereby a Python object hierarchy is converted into a byte stream, and “unpickling” is the inverse operation, whereby a byte stream (from a binary file or bytes-like object) is converted back into an object hierarchy.
Q156. Wat is de uitvoer van het volgende programma?
print("codescracker".endswith("er"))
-
True
-
1
-
2
-
False
Q157. Is de lijst veranderlijk in Python?
- Waar
- niet waar
Q158. Wat is de uitvoer van het volgende programma?
print("programming".center())
-
cr
-
programming
- Fout zegt
TypeError: center expected at least 1 argument, got 0
. - Geen van bovenstaande.
referentie. Het centrum() methode zal de string centreren, met behulp van een opgegeven teken (spatie is de standaardinstelling) als vulteken.
Syntaxis: string.center(length, character)
waar length
Is benodigd!
Q159. Wie heeft de programmeertaal Python gemaakt?
- Tim Berners-Lee
- Ada Lovelace
- Guido van Rossum
- Alan Turing
Q160. Welke collectie is besteld, veranderlijk, en staat dubbele leden toe?
- Set
- Tupel
- Woordenboek
- Lijst
Q161. Wat wordt er in de console afgedrukt als u deze code uitvoert?
x = 1j
print(x**2 == -1)
- Een runtimefout die aangeeft dat de variabele
j
is niet geïnitialiseerd. -
True
-
1j
-
False
Explanation: De brief j
fungeert als de denkbeeldige eenheid in Python, daarom x**2
middelen j**2
wat gelijk is aan -1
. de verklaring x**2 == -1
wordt beoordeeld als True
.
Q162. Wat wordt er in de console afgedrukt als u deze code uitvoert?
print(0xA + 0xB + 0xC)
-
33
-
63
-
0xA + 0xB + 0xC
-
None
Explanation: A
, B
en C
zijn hexadecimale gehele getallen met waarden 10
, 11
en 12
respectievelijk, dus de som van A
, B
en C
is 33
.
Q163. Wat zal deze code op het scherm weergeven?
for i in range(5):
print(i)
else:
print("Done!")
-
1 2 3 4 5 Done!
-
0 1 2 3 4 5 Done!
-
0 1 2 3 4 Done!
- U krijgt een syntaxisfout.
Q164. Welke vergelijking van lijsten en tupels in Python is correct?
- Use lists instead of tuples when you have a collection of related but dissimilar objects.
- Use tuples instead of lists when you have a common collection of similar objects.
- Use tuples instead of lists for functions that need to return multiple values.
- Use lists instead of tuples when the position of elements is important.
Q165. Consider the following code snippet that uses decorators to calculate the execution time of the execution_fn
functie:
import functools
import time
def timer(MISSING_ARG_1):
@functools.wraps(func)
def wrapper(*args, **kwargs):
start_time = time.perf_counter()
rval = func(*args, **kwargs)
end_time = time.perf_counter()
duration = end_time - start_time
print(f"Executed in {duration:.4f} seconds")
return MISSING_ARG_2
return MISSING_ARG_3
@timer
def execution_fn():
for i in range(3):
time.sleep(1)
execution_fn()
Which of the following choices are the missing arguments?
- :
MISSING_ARG_1 = wrapper
MISSING_ARG_2 = rval
MISSING_ARG_3 = func
- :
MISSING_ARG_1 = func
MISSING_ARG_2 = rval
MISSING_ARG_3 = wrapper
- :
MISSING_ARG_1 is empty
MISSING_ARG_2 = rval
MISSING_ARG_3 = wrapper
- :
MISSING_ARG_1 is empty
MISSING_ARG_2 = rval
MISSING_ARG_3 = func
Q166. Which of the following statements defines a new object type named Dog
in Python?
-
class Dog:
-
Dog class:
-
Dog:
-
class Dog
Q167. To use pipelines in scikit-learn
, import from the scikit-learn._
submodule.
-
preprocessing
-
pipeline
-
filters
-
pipe_filter
referentie The correct syntax is actually: from sklearn.pipeline import Pipeline
Q168. You should pass in a value of _ for the axis argument to the Pandas apply method to apply the function to each row.
- rij
- col
- 1
- 0
Q169. Data points in Pyplot are called…
- … pointers.
- … punten.
- … markers.
- … none of these.
Q170. What does this code print?
a = np.array([[1, 2], [3, 4], [5, 6]])
c = a[(a > 3) & (a < 11)]
print(c)
-
[[3, 4], [5, 6]]
-
[False, False, False, True, True, True]
-
[[0,0], [3, 4], [5, 6]]
-
[4 5 6]
Q171. Aannemen m
, n
, en p
are positive integers. In the following comprehension, how many times will the function randint
be called?
[ [ [ randint(1,100) for i in range(m) ] for j in range(n) ] for k in range(p) ]
-
m * n * p
- The greater value of
(m,n,p)
. - 1 miljoen.
-
m + n + p
Q172. Suppose you have a class named MyClass
which has multiple inheritance and methods with the same name in its ancestors. Which class method could you call to see which method will get priority when invoked?
-
MyClass.__mro__
-
MyClass.hierarchy()
-
callable(MyClass)
-
dir(MyClass)
Explanation: MRO stands for Method Resolution Order. It returns a list of types the class is derived from, in the order they are searched for methods.
Q173. Suppose you have a list of employees described by the code below. You want to assign Alice the same salary as Charlie. Which choice will accomplish that?
employees = {
'alice':{
'position':'Lead Developer',
'salary':1000
},
'bob':{
'position': 'Lead Artist',
'salary':2000
},
'charlie':{
'position':'cfo',
'salary':3000
}
}
-
employess['alice']['salary'] = employees['charlie']['salary']
-
employees.alice.salary = employees.charlie.salary
-
employees['alice'][1] = employees['charlie'][1]
-
employees['alice'].salary = employees['charlie'].salary
Explanation: This is accessing a key in a dictionary nested inside another dictionary. The command employees['alice']['salary'] = employees['charlie']['salary']
assigns the value of the salary
key in the dictionary of the employee charlie
to the value of the salary
key in the dictionary of the employee alice
.
Q174. You are given this piece of code. Aannemen m
en n
are already defined as some positive integer value. When it completes, how many tuples will my list contain?
mylist = []
for i in range(m):
for j in range(n):
mylist.append((i,j))
-
m
-
m + n
-
n
-
m \* n
Explanation: This code will run for m
X n
tijden, if you run this code, it will create m
X n
tuples.
The first loop runs for m
times and the inner loop will run for n
tijden. The single iteration of the first loop will only be completed when all of the n
iterations of an inner loop are completed. This is the same process for 2nd, and 3rd, … m
th iterations for outer loop. globaal, both loops will run m
X n
tijden.
Q175. What will this comprehension provide you?
{x : [y for y in range (1, x) if x % y == 0] for x in range (2, 100)}
- A dictionary whose keys are the numbers from 2 naar 99 (inclusief), and their respective values are their factors.
- A dictionary whose keys are the numbers from 2 naar 99 (inclusief), and their respective values are a list from 1 to the key value itself (inclusief).
- A dictionary whose keys are the numbers from 2 naar 99 (inclusief), and their respective values are the even numbers from 1 to the key value itself (inclusief).
- A dictionary whose keys are the numbers from 2 naar 99 (inclusief), and their respective values are the odd numbers from 1 to the key value itself (inclusief).
Q176. What is a common use of Python’s sys library?
- to take a snapshot of all the packages and libraries in your virtual environment
- to connect various systems, such as connecting a web front end, an API service, a database, and a mobile app
- to capture command-line arguments given at a file’s runtime
- to scan the health of your Python ecosystem while inside a virtual environment
Q177. What is the output of 17 % 15 ?
- 17
- 15
- 2
- 16
Q178. How would you create a list of tuples matching these lists of characters and actors?
characters = ["Iron Man", "Spider Man", "Captain America"]
actors = ["Downey", "Holland", "Evans"]
#example output : [("Iron Man", "Downey), ("Spider Man", "Holland"), ("Captain America", "Evans")]
- zip (karakters, actors)
- {X:y for x in characters for y in actors}
- [(X,en) for x in characters for y in actors]
-
d = {}
for x in range(1, len(characters)):
d[x] = actors [x]
Q179. Wat zal deze code op het scherm weergeven?
for i in range(5):
print (i)
else:
print("Done!")
- :
1
2
3
4
Done!
- U krijgt een syntaxisfout.
- :
0
1
3
4
5
Done!
- :
1
3
4
5
Done!
Q180. When is the if __name__ == "__main__":
block executed in a Python script?
- Always, as it is required in every Python script.
- Only when the script is executed directly from the command line or as the main program.
- Only when the script contains syntax errors.
- Only when the script is imported as a module in another script.
De if __name__ == "__main__":
blok wordt uitgevoerd wanneer het script rechtstreeks wordt uitgevoerd, maar niet wanneer het als module in een ander script wordt geïmporteerd. referentie
Q181. Wat zal de uitvoer zijn van de volgende Python-code?
def square(x):
return x * x
numbers = [1, 2, 3, 4, 5]
squared_numbers = map(square, numbers)
result = list(squared_numbers)
print(result)
-
[1, 4, 9, 16, 25]
-
[1, 2, 3, 4, 5]
-
[1, 8, 27, 64, 125]
-
[2, 4, 6, 8, 10]
De code definieert a square
functie om het kwadraat van een getal te berekenen. Er wordt dan gebruik gemaakt van de map
functie om deze functie toe te passen op elk element in de numbers
lijst, resulterend in een nieuwe iterabele. Tenslotte, de list
constructor wordt gebruikt om deze iterabele om te zetten in een lijst. De uitvoer is een lijst met kwadratische getallen. referentie
Q182. Welke van de volgende is geen geldige ingebouwde functie in Python?
- int
- string
- Booleaans
- reeks
Q183. Welke van de volgende is geen geldig Python-gegevenstype?
- int
- verkoold
- vlot
- str
In Python, welke functie wordt gebruikt om een regel van de console-invoer te lezen?
Q184.- invoer()
- lees_lijn()
- console_invoer()
- lijn krijgen()
Q185.1. Wat zal de uitvoer zijn van de volgende Python-code?
print("Hello {name1} and {name2}".format(name1='foo', name2='bin'))
- Hallo foo en bin
- Hallo {naam1} en {naam2}
- Fout
- Hallo en
Laat een antwoord achter
Je moet Log in of registreren om een nieuwe opmerking toe te voegen .