Negatives and positive results in lists

I am trying to write a function that allows me to add only positive numbers in a list and only negative numbers in a list. However, I do not know where to start with my encoding. Any help would be greatly appreciated!

Example:

negpos([-5,5,6,-8,9])

should return:

[-13, 20]
+3
source share
6 answers

Try this for size:

def negpos (lst):
    (neg, pos) = (0, 0)
    for elem in lst:
        if elem < 0:
            neg = neg + elem
        else:
            pos = pos + elem
    return [neg, pos]

print negpos ([-5,5,6,-8,9])

It just supports two batteries and adds the appropriate one to them. Output:

[-13, 20]

optional.

+7
source

filter sum, filter - , True, , False - . , 0, , 0, sum. , , , , , .

+2

:

def negpos( inlist ):
    p = sum(x for x in inlist if x > 0)
    n = sum(x for x in inlist if x < 0)
    return (n,p)

, , .

+1

-

>>> neg=0
>>> pos=0
>>> for i in [-5,5,6,-8,9]:
...   if i<0: neg+=i
...   if i>0: pos+=i
...
>>> print neg,pos
-13 20
0

sum - :

positive_tally = sum(x for x in seq if x > 0)
negative_tally = sum(x for x in seq if x < 0)

Combining these functions into one function negposwould be simple enough, but probably unnecessary, if you do not do it in several different places.

Out of curiosity, I decided to make an actual time comparison between the generator expression approach and a simple loop for:

code1 = """
data = [-5,5,6,-8,9]
def negpos(seq):
  neg, pos = 0, 0
  for x in seq:
    if x >= 0:
      pos += x
    else:
      neg += x
  return neg, pos
"""
code2 = """
data = [-5,5,6,-8,9]
def negpos(seq):
  neg = sum(x for x in seq if x < 0)
  pos = sum(x for x in seq if x > 0)
  return neg, pos
"""
command = "negpos(data)"
timer1 = timeit.Timer(command, code1)
timer2 = timeit.Timer(command, code2)
timer1.repeat()
timer2.repeat()

On my system, a dedicated loop forturns out to be about twice as fast (which is not particularly surprising since the loop runs twice using a generator-based approach, but it’s still interesting to confirm it).

0
source
import functools
import operator

ltzero = functools.partial(operator.ge, 0)  # 0>=num -> num<0
gtzero = functools.partial(operator.le, 0)  # 0<=num -> num>0

def negpos(lst):
    return [sum(filter(ltzero, lst)), sum(filter(gtzero, lst))]

negpos([-5,5,6,-8,9])  # ->  [-13, 20]
0
source

Source: https://habr.com/ru/post/1793493/


All Articles