DEV Community

Cover image for Default Arguments - HackerRank Solution Python
Deepak Raj
Deepak Raj

Posted on • Originally published at codeperfectplus.com on

Default Arguments - HackerRank Solution Python

Default arguments are a feature of many programming languages that allow you to specify a value for an argument that is not explicitly provided by the caller. This can be useful for making your code more concise and reusable.

Problem Statement and Explanation

Python supports a useful concept of default argument values. For each keyword argument of a function, we can assign a default value which is going to be used as the value of said argument if the function is called without it.

Default Arguments Solution in Python

Explanation of Solution

  • The code you have given defines two classes, EvenStream and OddStream. Each class has a method called get_next() which returns the next even or odd number, respectively. The function print_from_stream() takes an integer n as input and prints the first n even or odd numbers, depending on the value of the stream parameter.

  • The main function first reads the number of queries from the user. Then, it loops over the queries. In each iteration, it reads the name of the stream and the number of numbers to print from the user. It then calls the print_from_stream() function, passing the number of numbers to print and the appropriate stream object.

For example, if the user enters the following input:

  • even 5

then the main function will call the print_from_stream() function with the following arguments:

  • n = 5 and stream = EvenStream() and the print_from_stream() function will print the first 5 even numbers.

0 2 4 6 and 8

The problem statement is taken from Hackerrank, and the solutions are implemented by the CodePerfectPlus team

Other Article By Author

30 Days of Code SubReddit

Top comments (0)