user5367640
user5367640

Reputation:

Sum a list of numbers until a number X is found

In my program I need to put a while function which sums this list until a particular number is found:

[5,8,1,999,7,5]

The output is supposed to be 14, because it sums 5+8+1 and stops when it finds 999.

My idea looks like:

def mentre(llista):
  while llista != 999:
    solution = sum(llista)
return solution

Upvotes: 1

Views: 5703

Answers (4)

Andrew Winterbotham
Andrew Winterbotham

Reputation: 1010

An example of explicitly using a while loop would be as follows:

def sum_until_found(lst, num):
    index = 0
    res = 0
    if num in lst:
        while index < lst.index(num):
            res += lst[index]
            index += 1
    else:
        return "The number is not in the list!"
    return res

Another possible way is:

def sum_until_found(lst, num):
    index = 0
    res = 0
    found = False
    if num in lst:
        while not found:
            res += lst[index]
            index += 1
            if lst[index] == num:
                found = True
    else:
        return "The number is not in the list!"
    return res

There's many ways of doing this without using a while loop, one of which is using recursion:

def sum_until_found_3(lst, num, res=0):
    if num in lst:
        if lst[0] == num:
            return res
        else:
            return sum_until_found_3(lst[1:], num, res + lst[0])
    else:
        return "The number is not in the list!"

Finally, an even simpler solution:

def sum_until_found(lst, num):
    if num in lst:
        return sum(lst[:lst.index(num)])
    else:
        return "The number is not in the list!"

Upvotes: 1

Alex Riley
Alex Riley

Reputation: 177048

Since you mention using a while loop, you could try a generator-based approach using itertools.takewhile:

>>> from itertools import takewhile
>>> l = [5,8,1,999,7,5]
>>> sum(takewhile(lambda a: a != 999, l))
14

The generator consumes from the list l as long as the predicate (a != 999) is true, and these values are summed. The predicate can be anything you like here (like a normal while loop), e.g. you could sum the list while the values are less than 500.

Upvotes: 2

Bhargav Rao
Bhargav Rao

Reputation: 52181

Use index and slice

def mentre(llista):
    solution = sum(lista[:lista.index(999)])
    return solution

Demo

>>> lista =  [5,8,1,999,7,5] 
>>> sum(lista[:lista.index(999)])
14

Upvotes: 0

Daniel
Daniel

Reputation: 42778

Use the iter-function:

>>> l = [5,8,1,999,7,5]
>>> sum(iter(iter(l).next, 999))
14

iter calls the first argument, until the second argument is found. So all numbers are summed up, till 999 is found.

Upvotes: 2

Related Questions