简体   繁体   English

求列表的 n 次方

[英]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.给定一个包含正数和非负数 N 的数组。您应该找到数组中索引为 N 的元素的 N 次方。如果 N 在数组之外,则返回 -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.它正确地执行了第二部分,但是当变量 n 更大时,数组列表 output 不像它应该的那样 output -1。 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.因此,如果索引有错误,它将返回 -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.最初它按预期工作,但是当第 N 个数字等于数组元素的数量时会出现错误。 For example N is 4 and I have [1,2,3,4.例如 N 是 4,我有 [1,2,3,4。 Any idea why instead of returning -1 it returns NaN?知道为什么不返回 -1 而返回 NaN 吗?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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