简体   繁体   中英

Not fining last element in list

What I'm trying to do is taking the even indexes of a list then adding them together and lastly multiplying the total with the last element in the list. When I try with a set of negative numbers then suddenly its multiplying with index[1]

def checkio(array: list) -> int:
    """
        sums even-indexes elements and multiply at the last
    """
    total = 0
    evennumbs = []
    if len(array) == 0:
        return 0
    for i in array:
        if array.index(i) % 2 == 0:
            evennumbs.append(i)
    for e in evennumbs:
        #print(total, " + ", e, " = ")
        total += e
    print(evennumbs)
    print(total)
    total = total * array[-1]
    return total


# These "asserts" using only for self-checking and not necessary for auto-testing
if __name__ == '__main__':
    (checkio([-37,-36,-19,-99,29,20,3,-7,-64,84,36,62,26,-76,55,-24,84,49,-65,41]))

    #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"

This is the output I'm getting

[-37, -19, 29, 3, -64, 36, 26, 55, -65]
-36

-36 is the number it's multiplying with instead of 41.

Your function would be simplified a lot using slicing:

def checkio(array: list) -> int:
    if not array:
        return 0
    return sum(array[::2])*array[-1]
                                 
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"

Aside from the useless need for loops in your solution, this bit in particular is incorrect:

    for i in array:
        if array.index(i) % 2 == 0:
            evennumbs.append(i)

this would fail on input such as [1,2,3,3] or [1,2,2,3] as list.index always returns the first occurrence

array.index(i) returns the index of the first occurrence of i in array . The first occurrence of the value 84 in your test array is on an odd index, although it later occurs on an even index as well, and so you are losing it.

You should probably simply loop over the indices directly.

    for i in range(0, len(array)+1, 2):
        evennumbs.append(array[i])

But of course, this can be simplified to just

    evennumbs = array[::2]

and so the entire function can be simplified to

from typing import List

def checkio(array: List[int]) -> int:
    if len(array) == 0:
        return 0
    return sum(array[::2]) * array[-1]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM