0

Today get the interesting result when creating a new solution for the task by list comprehension.

def checkio(array: list) -> int:
 if array:
    return sum([x for x in array if array.index(x) % 2 == 0]) * array[-1]
 else: 
    return 0

assert checkio([0, 1, 2, 3, 4, 5]) == 30, "(0+2+4)*5=30"
assert checkio([1, 3, 5]) == 30, "(1+5)*5=30"
assert checkio([6]) == 36, "(6)*6=36"
assert checkio([]) == 0, "An empty array = 0"
assert checkio([-37,-36,-19,-99,29,20,3,-7,-64,84,36,62,26,-76,55,-24,84,49,-65,41]) == 1968

When I decided to do debugging I have seen that the sixteenth element was skipped. Why? On the Internet, I didn't find describe this cause.

1 Answers1

0

array.index(x) will return the index of the first occurrence of that value, thus if you have duplicates in the array that would not work. You can look at this answer, you could achieve what you want with a list slicing:


arr = [-37,-36,-19,-99,29,20,3,-7,-64,84,36,62,26,-76,55,-24,84,49,-65,41]
print(arr[::2])

Out:
[-37, -19, 29, 3, -64, 36, 26, 55, 84, -65]
Yolao_21
  • 765
  • 1
  • 4
  • 10