Hackerrank Python Data Structures & Algorithms 2 — Questions and Answers
Question 1: What is the purpose of the `__init__` method in a Python class?
- To initialize the attributes of a new object when it is created (Correct answer)
- To destroy an object when it is no longer needed
- To define the string representation of an object
- To compare two objects for equality
Correct answer: To initialize the attributes of a new object when it is created
The __init__ method is the constructor that runs automatically when a new instance of a class is created, allowing you to set initial values for the object's attributes.
Question 2: What does the `lambda` keyword create in Python?
- An anonymous (unnamed) function defined in a single expression (Correct answer)
- A new class definition
- A global variable
- A loop that runs indefinitely
Correct answer: An anonymous (unnamed) function defined in a single expression
Lambda creates a small anonymous function that can take any number of arguments but can only contain a single expression. It is often used with functions like map(), filter(), and sorted().
Question 3: What is the output of: print(type({}))?
- <class 'dict'> (Correct answer)
- <class 'set'>
- <class 'list'>
- <class 'tuple'>
Correct answer: <class 'dict'>
Empty curly braces {} create an empty dictionary in Python, not an empty set. To create an empty set, you must use set(). This is a common Python gotcha.
Question 4: Which method would you use to remove and return the last element from a Python list?
- pop() (Correct answer)
- remove()
- del
- discard()
Correct answer: pop()
The pop() method without arguments removes and returns the last element of a list. With an index argument, it removes and returns the element at that position.
Question 5: What is a Python generator and how does it differ from a regular function?
- A function that uses yield to produce a sequence of values lazily, one at a time (Correct answer)
- A function that generates random numbers
- A class that creates new objects
- A built-in function for creating lists
Correct answer: A function that uses yield to produce a sequence of values lazily, one at a time
Generators use the yield keyword to produce values one at a time on demand (lazy evaluation), saving memory compared to creating an entire list. They maintain state between yields.
Question 6: What does the `*args` parameter allow in a Python function definition?
- Accepting a variable number of positional arguments as a tuple (Correct answer)
- Accepting only keyword arguments
- Limiting the function to exactly one argument
- Creating a list of return values
Correct answer: Accepting a variable number of positional arguments as a tuple
*args collects any number of positional arguments into a tuple, allowing the function to be called with varying numbers of arguments. Similarly, **kwargs collects keyword arguments into a dictionary.
What is the purpose of the `__init__` method in a Python class?