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
There are 2 problems with your code. First, it should be if x < 0
instead of if args < 0
because x is an element in args. Second, you have a return inside the loop, so it ends the function after increasing the neg_count
by one.
This code may be better and shorter;)
only_neg = [num for num in args if num < 0]
neg_count = len(only_neg)
or
neg_count = sum(1 for i in args if i < 0)
There are a couple issues with your code:
args
ends up being a list with one element, the list you're passing in your driver.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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.