We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
- Prepare
- Python
- Debugging
- Default Arguments
- Discussions
Default Arguments
Default Arguments
Sort by
recency
|
213 Discussions
|
Please Login in order to post a comment
Here is HackerRank Default Arguments in Python solution - https://programmingoneonone.com/hackerrank-default-arguments-problem-solution-in-python.html
the problem is poorly described, the task itself is simple, but it is not clear what the author means...
class EvenStream: def init(self): self.current = -2
class OddStream: def init(self): self.current = -1
def print_from_stream(n, stream=None): if stream is None: stream = EvenStream() for _ in range(n): print(stream.get_next())
Read input from STDIN
q = int(input()) for _ in range(q): stream_name, n = input().split() n = int(n) if stream_name == "even": print_from_stream(n, EvenStream()) else: print_from_stream(n, OddStream())
Mutable default arguments (like lists and dictionaries) in Python functions are created only once when the function is defined. If you don't provide your own argument when calling the function, it will keep using and modifying that same original mutable object across different calls, leading to unexpected results. The solution is to use None as the default and create a new mutable object inside the function if the default is used.
Same problem can be found in below function. def add_to_list_bad(item, my_list=[]): my_list.append(item) return my_list