0

create a function that when given list of integers, returns a list,where the first element is the count of positive numbers and the second element is the sum of negative numbers. NB: Treat 0 as positive.

Functions that deal with data structures

7th Sep 2016, 2:37 PM
brian
3 Respuestas
0
def sum_by_sign(src): dst = [0,0] dst[0] = sum(filter(lambda x: x >= 0, src)) dst[1] = sum(filter(lambda x: x < 0, src)) return dst numbers = list(map(int, input("enter numbers in single line, separated with spaces:\n").split())) sums = sum_by_sign(numbers) print("sum of positive elements: {0}".format(sums[0])) print("sum of negative elements: {0}".format(sums[1])) ------- I would use dictionary for output to access sums with keys like 'negatives', 'positives' or smth like that, instead of indices. It seems to make program more clear for understanding.
8th Sep 2016, 4:33 AM
Textobot
Textobot - avatar
0
thank you Textobot, could you please assist with the one that uses dictionaries?
9th Sep 2016, 7:35 PM
brian
0
the same with dictionary: ---------------------------- def sum_by_sign(src): dst = {'positive':0,'negative':0} dst['positive'] = sum(filter(lambda x: x >= 0, src)) dst['negative'] = sum(filter(lambda x: x < 0, src)) return dst numbers = list(map(int, input("enter numbers in single line, separated with spaces:\n").split())) sums = sum_by_sign(numbers) print("sum of positive elements: {0}".format(sums['positive'])) print("sum of negative elements: {0}".format(sums['negative']))
13th Sep 2016, 9:36 AM
Textobot
Textobot - avatar