Home > Net >  Sum list elements when sum is not greater than given interval, else skip element
Sum list elements when sum is not greater than given interval, else skip element

Time:06-22

I have a list of numbers and I need to get some of these, but: list element should be skipped if sum this element is bigger or smaller than given numbers in interval. I try to do continue within for loop, but smth is wrong and I do not understand what. How can I do this in correct way? Thanks in advance

I tried this (sum should start from 1)

numbers = [3,2,-3,-1,5,7,-1,-2]
interval = [-1,0,1,2,3,4,5,6,7,8,9]
sum = 1

for i in range(0,len(numbers)):
    sum = sum   numbers[i]
    if sum not in interval:
        continue
    print(sum)

So,

    1 3 2=6 <- its ok
    6 (-3) = 3 <- its ok
    3 (-1) = 2 <- its ok
    2  5 = 7 ok

7 7 = 14 <- thats not ok

because 14 is not in interval. So if its not in interval loop should skip 7 value and goes to -1 value.

CodePudding user response:

Your question is a bit unclear. But right now you are doing these steps:

  • go through each element in numbers
  • add next element to sum
  • check if sum is in not in interval
  • if true continue
  • print sum

To me it is usually easier to think the other way, if it is in interval then I want something to happen. As I understood your question is that you want to print these numbers:

4 6 3 2 7 6 4

This code should do the trick:

numbers = [3,2,-3,-1,5,7,-1,-2]
interval = [-1,0,1,2,3,4,5,6,7,8,9]
sum = 1

for i in range(0,len(numbers)):
    if (sum   numbers[i]) in interval:
        sum = sum   numbers[i]
        print(sum)

But if you want to do your logic, if would put the adding inside an else like this:

numbers2 = [3,2,-3,-1,5,7,-1,-2]
interval2 = [-1,0,1,2,3,4,5,6,7,8,9]
sum2 = 1

for j in range(0,len(numbers2)):
    if sum2   numbers2[j] not in interval2:
        continue
    else:
        sum2 = sum2   numbers2[j]
        print(sum2)

CodePudding user response:

numbers = [3,2,-3,-1,5,7,-1,-2]
interval = [-1,0,1,2,3,4,5,6,7,8,9]
sum = 1

for i in range(0,len(numbers)):
    if sum in interval:
        sum = sum   numbers[i]
        print(sum)
  • Related