List operation quiz
I’ve tried a quiz on CheckIO. Here’s the description:
You are given an array of integers. You should find the sum of the elements with even indexes (0th, 2nd, 4th…) then multiply this summed number and the final element of the array together. Don’t forget that the first element has an index of 0.
My first answer is as follows:
#!/usr/bin/env python3
checkio = lambda v: sum(v[::2]) * v[-1]
# Test cases
if __name__ == '__main__':
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"
Frankly speaking, it’s wrong. When an arg of checkio
is an empty list, v[-1]
will be IndexError
.
To fix it, I’ve made a change as follows:
checkio = lambda v: sum(v[::2]) * (0 if len(v) == 0 else v[-1])
It works, but (0 if len(v) == 0 else v[-1])
can be replaced with sum(v[-1:])
since it’ll be 0
when v
is the empty list. As a result, following one is totally valid:
checkio = lambda v: sum(v[::2]) * sum(v[-1:])
:)