简体   繁体   中英

Calculating the sum of the list and removing -1 values

I want to write a python program where given a user input list if the last element is -1 print -1, then if any element of the list contains -1 that should not be count and remaining array sum.

Eg:

1) list=[1,2,3,4,5] ans should be 15 

2) list=[1,2,3,4,-1] ans should be -1
3) list=[1,2,-1,4,5] ans should be 12 ignoring "-1"

I have tried 2 solutions but none working.

import sys
def totalcost(ar):

  if ar[-1]==-1:
    return -1
  else:
    summ=0
    for elem in ar:
        if(ar[elem]==-1):
            ar.remove(elem)
            summ=summ+elem
        else:        
            summ=summ+elem      
        return summ
if __name__=='__main__':
  ar_city=input()
  ar=list(map(int,input().strip().split()))
  result=totalcost(ar)
  print(result)  
import sys
def totalcost(ar):

  if ar[-1]==-1:
    return -1
  else:
    summ=0
    for elem in ar:
        if(ar[elem]<0):
            ar_new=ar.remove(elem)
            for i in ar_new:
                summ=summ+i
        else:        
            summ=summ+elem      
        return summ
if __name__=='__main__':
  ar_city=input()
  ar=list(map(int,input().strip().split()))
  result=totalcost(ar)
  print(result)  

Here is a possible solution:

def totalcost(ar):
    return -1 if ar[-1] == -1 else sum(x for x in ar if x != -1)

If you don't want a one line solution that uses list comprehensions, you can do something like this:

def totalcost(ar):
    if ar[-1] == -1:
        return -1
    s = 0
    for x in ar:
        if x != -1:
            s += x
    return s

You could use some simple functions that would make your life better:

sum(filter(lambda x: x != -1, ls))
  1. sum - sum the iterable without using for loops
  2. filter - filter out unwanted elements from iterable. In this case, I filter out all -1 from ls using the simple lambda x: x != -1 .

Of course, this should be used after your initial condition, like this:

if ls[-1] == -1:
    return -1
return sum(filter(lambda x: x != -1, ls))

If you want, you can read about list comprehension vs. lambda + filter here

I think you could simply implement using filter and sum as well as lambda. Just slightly updated your totalcost function

import sys
def totalcost(ar):
    if ar[-1] == -1:
        return -1
    else:
        ar_filtered = filter(lambda x: x > 0, ar)

        return sum(ar_filtered)

if __name__ == '__main__':
    ar_city = [1, 2, 3, 4, 5]
    assert totalcost(ar_city) == 15

    ar_city = [1, 2, 3, 4, -1]
    assert totalcost(ar_city) == -1

    ar_city = [1, 2, -1, 4, 5]
    assert totalcost(ar_city) == 12

Lambda reference: https://realpython.com/python-lambda/

Here are the mistakes you have made:

  1. ar[elem] is not iterating each element in ar properly.
  2. You return the summ in the for-in loop, so it would return the the value of the first element only.

Here is an working example that modified from your code.

def totalcost(ar):
    if ar[-1] == -1:
        return -1
    summ = 0
    for elem in ar:
        if(elem != -1):
            summ += elem
    return summ

Added explanation for Riccardo's answer:

def get_sum(arr):
    return -1 if arr[-1] == -1 else sum(item for item in arr if item != -1)

Explanation

The first part in the function will return -1 If the last value of the list is -1 , then in the else part: it will make a list of items in list if the item is not -1 using list comprehension. Then it calls the built-in sum method to find the sum of the resulting list and returns it.

Read more

There are a lot of possible solutions to this problem. I am not writing a one-liner because others have already written it.
I am writing the solution which I believe is the simplest.

def total_sum(arr):
    if arr[-1]==-1:
        return -1
    sum_arr = 0
    for elem in arr:
        if elem == -1:
            continue
        else:
            sum_arr+=elem
    return sum_arr   

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM