0

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)  
hedy
  • 1,160
  • 5
  • 23
  • "none working" - please describe exactly what goes wrong. If you get an error, include the complete error traceback. If you get some wrong output, include test cases, the ouput you get vs the expected output. Also, it would be better to only include one piece of code. – Thierry Lathuille Aug 10 '20 at 08:38
  • here what wrong you are doing is this if(ar[elem]<0): this might give array out of bounds – gagangaur Aug 10 '20 at 08:38
  • Simply done, you could loop through the list and add current element to a predefined sum variable if it's not negative – Nehal Samee Aug 10 '20 at 08:39

6 Answers6

3

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
Riccardo Bucco
  • 13,980
  • 4
  • 22
  • 50
2

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

CIsForCookies
  • 12,097
  • 11
  • 59
  • 124
1

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/

Yuri R
  • 311
  • 2
  • 9
1

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
Riccardo Bucco
  • 13,980
  • 4
  • 22
  • 50
Andreas
  • 127
  • 8
0

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

Riccardo Bucco
  • 13,980
  • 4
  • 22
  • 50
hedy
  • 1,160
  • 5
  • 23
  • This is not "similar" to other answers, it's *identical* to my answer :) You could have edited my answer instead – Riccardo Bucco Aug 10 '20 at 08:43
  • @RiccardoBucco sorry I actually meant the answer that was deleted, don’t think I saw your answer when I answered it – hedy Aug 10 '20 at 08:45
  • Building an intermediate list in `sum([item for item in list if item != -1])` is useless and inefficient, just do `sum(x for x in ar if x != -1)` . – Thierry Lathuille Aug 10 '20 at 08:47
  • My answer was the very first one, so it's impossible you saw another answer and not mine. Anyway, at least don't use a reserved word ("list") for a variable, and don't create a useless list inside the `sum` function. – Riccardo Bucco Aug 10 '20 at 08:47
  • Thanks for the suggestions, I edited it. It might be because it didn’t pop up immediately after you posted your answer, but I gave you credit anyhow. And I will edit your answer instead in the future, thank you – hedy Aug 10 '20 at 08:51
0

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   
KUSHAGRA BANSAL
  • 85
  • 1
  • 10