0
list of integers and number python function to find and return the sum of elements of the list.Don't add given num and bef &aft
list =[1,2,3,4] output :4
7 Respuestas
+ 7
Can you explain step by step how you get the output 13 from a list [1, 2, 3, 7, 4, 6, 7, 1, 10] and the number 7? Do you want to add all numbers before the first 7 and after the last 7 in the list? So 1+2+3+1+10? But that's not 13?
/Edit: Do you mean add all numbers in the list and subtract the given number? 1 + 2 + 3 - 7 + 4 + 6 - 7 + 1 + 10 = 13...
ls = [1, 2, 3, 7, 4, 6, 7, 1, 10]
num = 7
print(sum([n if n != num else -n for n in ls])) # 13
/Edit²: I think I got you. Add all numbers in ls that are not equal to num and don't come right before or after num:
sum_ = 0
for i in range(len(ls)):
if not any(n == num for n in ls[i-1:i+2]):
sum_ += ls[i]
print(sum_) # 13
+ 7
Try this:
ls = [1, 7, 3, 4, 1, 7, 10 ,5]
num = 7
sum_ = 0
for i in range(len(ls)):
t = ls[max(0, i-1):i+2]
if not any(n == num for n in t):
sum_ += ls[i]
print(sum_) # 9
or a little more compact: print(sum([ls[i] for i in range(len(ls)) if not any(n == num for n in ls[max(0, i-1):i+2])]))
+ 1
Well Thank you for the perfect answer.
+ 1
def sum_of_elements(num_list,number):
for i in range(1, len(num_list)-1):
if num_list[i]==number:
num_list[i] = 0
num_list[i-1] = 0
if num_list[i+1]==number:
continue
else:
num_list[i+1] = 0
if num_list[0]==number:
num_list[0]=0
num_list[1]=0
if num_list[-1]==number:
num_list[-1]=0
num_list[-2]=0
result_sum = sum(num_list)
return result_sum
num_list=[1,7,3,4,1,7,10,5]
number=7
print(sum_of_elements(num_list, number))
0
well if I have a list with elements [1,2,3,7,4,6,7,1,10].If number=7 .I need the output to be printed as 13 that is leaving given number and also before and after numbers of 7 I need the sum.How to approach this problem
0
Here What I want to do is if given number is 7 and list is [1,7,3,4,1,7,10,5] the expected output is 9 as leaving 0+0+0+4+0+0+5=9 and printing 9 as output