简体   繁体   中英

Finding the nth power in a list

You are given an array with positive numbers and a non-negative number N. You should find the N-th power of the element in the array with the index N. If N is outside of the array, then return -1.

def index(array, n):
    selected_number = []
    if n > len(array):
        return -1
    else:
        selected_number.append(array[n])
        total = selected_number[0]
    return total ** n

This is the code I wrote. It does the second part correctly but when the variable n is greater the array list the output doesn't output -1 like it is supposed to. How does this not work?

Here is a one liner:

result = arr[n]**n if n<len(arr) else -1

Simply you can use:

def index(array,n):
    try:
        return array[n] ** n
    except IndexError:
        return -1

So, if there is an error with index it will return -1.

Another one liner:

def index(array, n):
    return sum(array[n:n+1])**n or -1

I have the code below for the same kata. Initially it works as it supposed to, but gives me errors when the Nth number is equal to the number of the array elements. For example N is 4 and I have [1,2,3,4. Any idea why instead of returning -1 it returns NaN?

function index(array, n){
  if (n > array.length){
    return -1;
  }
  indexNum = array[n] ** n;
  return indexNum;
}

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