Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python function that counts negative integers using arbitrary number of parameters

Python newbie here, I need help with working with function with arbitrary number of parameters.

I want to implement a function that can take an arbitrary number of parameters, and counts negative integers. I want to try the negative_counter function on the following list of numbers 4,-3,5,6,-7

See my attempt (not sure what I am doing wrong)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

def negative_counter(*args):
    # setting the negative count to 0
    neg_count = 0
    # iterating through the parameters
    for x in args:
    # negative numbers are less than 0
        if args < 0:
    # adding 1 to negative number
            neg_count = neg_count + 1
            return neg_count

# driver code 
negative_counter([4,-3,5,6,-7]) 

#Desired output should return 2 since -3 and -7 are the negative integers

Please publish your code as you respond. Thanks

>Solution :

There are a couple issues with your code:

  • You’ve specified that the function take a single variadic argument, as discussed in the Arbitrary Arguments List documentation. So, args ends up being a list with one element, the list you’re passing in your driver.
  • You need to perform a comparison against x instead of args.

Here are examples that show demonstrate working with variadic arguments as well as unpacking argument lists, along with a simplified implementation:

def negative_counter(*args):
    neg_count = 0
    for x in args:
        if x < 0:
            neg_count = neg_count + 1
    return neg_count

def negative_counter_list(num_list):
    neg_count = 0
    for x in num_list:
        if x < 0:
            neg_count = neg_count + 1
    return neg_count

def negative_counter_simplified(*args):
    return len([x for x in args if x < 0])

numbers = [4, -3, 5, 6, -7]

# use "*numbers" to unpack the list
print(negative_counter(*numbers))

# use the function that actually expects the list
print(negative_counter_list(numbers))

# use the simplified implementation, once again unpacking the list
print(negative_counter_simplified(*numbers)

Output:

$ python3 test.py
2
2
2
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading