+ 1
Need help to solve this problem
Given a list of integers and a number. Write a python function to find and return the sum of the elements of the list. Note: Don't add the given number and also the numbers present before and after the given number in the list. Sample input Expected output list=[1,2,3,4], number=2 4 list=[1,2,2,3,5,4,2,2,1,2],number=2 5 list=[1,7,3,4,1,7,10,5],number=7 9 list=[1,2,1,2],number=2 0
4 Answers
+ 3
def sum_of_elements(num_list,number):
temp=0
for i in range(1,len(num_list)-2):
if num_list[i]==number: # [1,7,3,4,1,7,10,5] equal to number
if num_list[i+1]==number: #for [1,2,2,3,4,2,8,9] equal to
temp += num_list[i+2] # number
else:
temp += num_list[i+2]
return temp
num_list=[1,7,3,4,1,7,10,5]
number=7
print(sum_of_elements(num_list, number))
number_list=[1,2,2,3,4,2,8,9]
number=2
print(sum_of_elements(number_list, number))
+ 1
I think you should attempt to find simpler conditions to test for.
You want to add a list item to temp, if it DOES NOT equal number (plus the items left and right of it).
I think it will be easier if you start with what you want:
if num_list[i] != number:
And if that is the case, you look left and right.
Wanna give it one more try?
(About the code as it is: The conditions don't seem to make sense.
if the number is equal, and the right of it is also equal, you just add the element two places from this one - but that might also be equal!
Furthermore you have the same statement in if and else.)
0
Please show us your attempt.
0
def sum_of_elements(num_list,number):
result_sum=0
i=0
while(i<len(num_list)):
if num_list[i]==number or (i+1<len(num_list) and num_list[i+1]==number) or (i-1>=0 and num_list[i-1]==number):
pass
else:
result_sum+=num_list[i]
i+=1
return result_sum
num_list=[1,7,3,4,1,7,10,5]
number=7
print(sum_of_elements(num_list, number))