Home > database >  When processing a list a specific value is skipped
When processing a list a specific value is skipped

Time:10-09

def checkio(array: list) -> int:
    """
    Sums even-indexes elements and multiply at the last
    """
    a = []
    if array:
        for i in array:
            if array.index(i) == 0 or array.index(i) % 2 == 0:
                a.append(i)
        print(a)
        return sum(a) * array[-1]
    else:
        return 0


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

The output for print(a) is [-37, -19, 29, 3, -64, 36, 26, 55, -65], but 84 is not included in the list. Why is it doing so?

CodePudding user response:

The index(i) method will always return the index of the first occurence of a value. Since the first occurrence of 84 is at an odd index (9) it is excluded every time it is encountered even if farther down the list there is an 84 at an even index (16).

If you want to select values at even indexes you could use the enumerate() function to get each item's index along with its value:

for index,value in enumerate(array):
    if index%2 == 0: 
        a.append(value)

If you're only going to add up the values, you don't need to place them in a separate list, you can simply keep a running total:

total = 0
for index,value in enumerate(array):
    if index%2 == 0: 
        total  = value

An even simpler way would be to use a striding subscript on the list to sum only the values at even indexes (i.e stepping by 2). Your function would then have only a single line:

return sum(array[::2]) * sum(array[-1:]) # zero if array is empty

CodePudding user response:

Because the index(x) method returns the position of the first value that is equal to x as written in Python documentation, you can find here:

https://docs.python.org/3/tutorial/datastructures.html

so the array.index(84) will return 9 and so it will not be appended to "a".

CodePudding user response:

array.index(i) will return the index of 1st occurrence of i, since you have two 84 but for both, it'll return index of 1st 84 which is 9 odd.
use enumerate()

for i,n in enumerate(array):
    if i % 2 == 0:
        a.append(n)
  • Related