Reputation: 13
New to using python. Was wondering how can I create a function to get the sum of numbers before a certain number in a list using while
loop. For example, I want to get the sum of all numbers before the number 3 pops up in the list [1,2,5,2,3,2] should result in 10. Using my faulty code, my function doesn't consider the 3 and just adds all the numbers.
def nothree(nt):
while nt != 3:
list_sum = sum(nt)
return list_sum
Upvotes: 1
Views: 652
Reputation: 164
def nothree(nt):
i = 0
sum = 0
while nt[i]:
if nt[i] is 3:
break
sum += nt[i]
i += 1
return sum
this is so you can keep the while loop for whatever reason. But also in python you could something like:
def nothree(nt):
for i in nt[:-2]:
sum += [i]
return list_sum
Upvotes: 1
Reputation: 2167
You can do it one line as well
nt = [1,2,5,2,3,2]
x = sum(nt[:nt.index(3)])
nt[:nt.index(3)]
will give you the list before 3
appears for the first time in the list. ie. [1, 2, 5, 2]
Upvotes: 0
Reputation: 73450
You can use itertools.takewhile
for this pattern:
from itertools import takewhile
def nothree(nt):
return sum(takewhile(lambda x: x != 3, nt))
>>> nothree([1, 2, 5, 2, 3, 1])
10
While Fejs has you covered with an instructive loop-based solution, I might add this one-line hack that works without any libraries:
return sum(x if x != 3 else next(iter([])) for x in nt)
where the StopIteration
raised by next(iter([]))
will stop the generator on the first 3
.
Upvotes: 0
Reputation: 2888
Something like this:
def nothree(nt):
sum = 0
for n in nt:
if n == 3:
break
sum += n
return sum
If there is 3 in list, it will break the loop and return sum of numbers before 3 was reached. If there is no 3 in list, the sum will be sum of the list. And finally, if there is no numbers in list, sum will be 0.
Upvotes: 0