Default Arguments

Sort by

recency

|

213 Discussions

|

  • + 0 comments

    Here is HackerRank Default Arguments in Python solution - https://programmingoneonone.com/hackerrank-default-arguments-problem-solution-in-python.html

  • + 0 comments

    the problem is poorly described, the task itself is simple, but it is not clear what the author means...

  • + 0 comments

    class EvenStream: def init(self): self.current = -2

    def get_next(self):
        self.current += 2
        return self.current
    

    class OddStream: def init(self): self.current = -1

    def get_next(self):
        self.current += 2
        return self.current
    

    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())

  • + 1 comment
    • 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

  • + 0 comments
    def print_from_stream(n, stream=None):
        if stream is None:
            stream = EvenStream()
        for _ in range(n):
            print(stream.get_next())