0

I got a list like this: my_list = [5, 9, 3, 4, 1, 8, 7, 6] And it can have an undefined number of integers in it. I need to perform a calculation between the numbers that ignores the second number and calculate something like this: (5 - 3) + (4 - 8) + 7 and then repeat the process.

I have tried a for loop like this one:

for i in range(0, len(my_list), 2):
    print(my_list[i])

But it seems wrong and I don't know how to proceed further.

Klein -_0
  • 158
  • 1
  • 13

3 Answers3

4

You want the sum:

  my_list[0] - my_list[2]
+ my_list[3] - my_list[5]
+ my_list[6] - ...

The elements in the left column, with a + sign, are the elements of the slice my_list[::3]. The elements in the right column, with a - sign, are the elements of the slice my_list[2::3].

Solution:

Thus the function you are looking for is:

def f(my_list):
  return sum(my_list[::3]) - sum(my_list[2::3])

# f([5, 9, 3, 4, 1, 8, 7, 6]) == 5

Iterating to print intermediary results:

If you want to print the intermediary results, you can iterate through my_list[::3] and my_list[2::3] simultaneously using itertools.zip_longest:

from itertools import zip_longest

for a,b in zip_longest(my_list[::3], my_list[2::3], fillvalue=0):
  print('{} - {} = {}'.format(a, b, a-b))

# OUTPUT:
# 5 - 3 = 2
# 4 - 8 = -4
# 7 - 0 = 7

See also:

Stef
  • 13,242
  • 2
  • 17
  • 28
1

A nice Pythonic way to achieve it would be with itertools:

from itertools import compress, cycle

my_list = [5, 9, 3, 4, 1, 8, 7, 6]
# Choose first and third items of each 3
narrowed = compress(my_list, cycle([1,0,1])) 
# Alternate between positive and negative numbers
signs = map(lambda x,y: x*y, narrowed, cycle([1,-1]))
# Sum everything
sum(signs)

Or in one line:

sum(map(lambda x,sign: sign*x, compress(my_list, cycle([1,0,1])), cycle([1,-1])))
  • cycle - infinitely repeat an iterator
  • compress - allow you to choose a subset by a bit sign
  • map - applies a function on an iterator
  • sum - sums
tmrlvi
  • 2,235
  • 17
  • 35
0

Simple and Efficient Solution.

score = 0
for i in range(0, len(my_list), 3):
    j = i+2
    if j < len(my_list):
        score +=  my_list[i] - my_list[j]
    else:
        score += my_list[i]
print(score)