Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Slice Notation Galore solution in Clear category for Even the Last by tigercat2000
def checkio(array):
"""
sums even-indexes elements and multiply at the last
"""
# An empty array will cause an index error for `array[-1]`, and the output expectations specifically state that it should be zero.
if len(array) < 1:
# So, check if it's an empty list, and return 0 straight away if that's the case.
return 0
# Initialize the return variable, and set it's default value to 0. This saves us the trouble of assigning the first number in the even array directly.
result = 0
# Use Python's slice notation to do a 2 step slice. [starting_index (default 0) : ending_index (default len(list) - 1) : step].
evens = array[::2]
# Cycle through every number in the resulting list.
for i in evens:
# Add them to the result variable initialized above. As it starts as `0`, we can just blindly add to it, no worries about it being uninitialized.
result = result + i
# Multiply the sum against the last array value.
# `[-1]` is the pythonic way to access the last element of an array.
result = result * array[-1]
# Return the final result.
return result
#These "asserts" using only for self-checking and not necessary for auto-testing
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"
Nov. 5, 2016
Comments: