In: Computer Science
Using Python
def specialAverage():
Print the number of 0s and then return the average of either the
positive
values in the list (if the optional parameter has value 1) or the
negative
values in the list (if the optional parameter has value 0).
Arguments:
a list of numbers : the list can contain any numeric values
an integer : this integer is an optional parameter and only takes
value
0 or 1, and defaults to 1 if the user does not specify the
value
when calling the function.
Return:
a number : the computed average of either positive or negative
numbers
rounded to 1 decimal place
>>> specialAverage([1,2,3,4,-1,-2,-3,-4],0)
-2.5
and also prints "There are 0 zeros in the list"
def specialAverage(lst, choice=1):
"""
Print the number of 0s and then return the average of either the positive
values in the list (if the optional parameter has value 1) or the negative
values in the list (if the optional parameter has value 0).
Arguments:
a list of numbers : the list can contain any numeric values
an integer : this integer is an optional parameter and only takes value
0 or 1, and defaults to 1 if the user does not specify the value
when calling the function.
Return:
a number : the computed average of either positive or negative numbers
rounded to 1 decimal place
"""
pos_total, pos_count, neg_total, neg_count, zero_count = 0, 0, 0, 0, 0
for num in lst:
if num > 0:
pos_count += 1
pos_total += num
elif num < 0:
neg_count += 1
neg_total += num
else:
zero_count += 1
print("There are {} zeros in the list".format(zero_count))
if choice == 1:
return pos_total / pos_count
else:
return neg_total / neg_count
print(specialAverage([1, 2, 3, 4, -1, -2, -3, -4], 0))
