views:

74

answers:

5

If i had a list of numbers and some maybe negative, how would i ensure all numbers in my list were positive? I can covert the items in the list to integers thats no problem.

Another question, I want to compare items in my list to an integer value say 'x' and sum all the values in my list that are less than x.

Thank you.

A: 
# input list is named "lst"
pos_list = [int(a) for a in lst if int(a) > 0]
# And num 2 (notice generator is used instead of list)
return sum(a for a in lst if a < x)
Hamish Grubijan
Hm ... asker, did you want to throw out the negative numbers or flip their sign?
Hamish Grubijan
A: 
>>>mylist = [1,2,3,-2]
>>>any(item for item in mylist if item < 0)
True
>>>mylist.pop()
-2
>>>any(item for item in mylist if item < 0)
False

answers your first question.

>>> x = 3
>>> sum(item for item in mylist if item < x)
3

answers your second question.

Tim Pietzcker
+4  A: 

If you have a list Ns of numbers (if it's a list of strings as in several similar questions asked recently each will have to be made into an int, or whatever other kind of number, by calling int [[or float, etc]] on it), the list of their absolute values (if that's what you mean by "ensure") is

[abs(n) for n in Ns]

If you mean, instead, to check whether all numbers are >= 0, then

all(n >= 0 for n in Ns)

will give you a bool value respecting exactly that specification.

The sum of the items of the list that are <x is

sum(n for n in Ns if n < x)

Of course you may combine all these kinds of operations in one sweep (e.g. if you need to take the abs(n) as well as checking if it's < x, checking if it's >= 0, summing, whatever).

Alex Martelli
A: 

Answer / First part:

>>> a = [1, 2, -3, 4, 5, 6]
>>> b = [1, 2, 3, 4, 5, 6]

>>> max(map(lambda x: x < 0, a))
False

>>> max(map(lambda x: x < 0, b))
True

Or just use min:

>>> min(a) < 0
True

>>> min(b) < 0
False

Second part:

>>> x = 3
>>> sum(filter(lambda n: n < x, a))
>>> 0

>>> sum(filter(lambda n: n < x, b))
>>> 3
The MYYN
A: 

If I understand correctly your question, I guess you are asking because of some class about functional programming.

In this case, what you are asking for can be accomplished with functional programming tools available in Python.
In particular, the first point can be solved using filter, while the second with map and reduce (or, better, with map and sum).

Roberto Liffredo