Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Simplistic Solution. solution in Clear category for Index Power by tigercat2000
def index_power(array, n):
"""
Find Nth power of the element with index N.
"""
if len(array) - 1 < n:
# Length of the array (number of elements it contains) minus one (last index of the array) is still less than the requested index.
# This means that the index does not exist, therefore, we must return -1.
return -1
# Access the array index [n] and assign it to the new variable `i`.
i = array[n]
# Use the pow (power) function to set `i` equal to the power of `i` pow `n`.
# We don't bother to initialize a new variable in order to save memory- `i` will retain it's value until the `pow` function returns the correct value.
i = pow(i, n)
# Return the finished value.
return i
if __name__ == '__main__':
#These "asserts" using only for self-checking and not necessary for auto-testing
assert index_power([1, 2, 3, 4], 2) == 9, "Square"
assert index_power([1, 3, 10, 100], 3) == 1000000, "Cube"
assert index_power([0, 1], 0) == 1, "Zero power"
assert index_power([1, 2], 3) == -1, "IndexError"
Nov. 5, 2016