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)
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,
argsends up being a list with one element, the list you’re passing in your driver. - You need to perform a comparison against
xinstead ofargs.
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