0

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?

quamrana
  • 37,849
  • 12
  • 53
  • 71
Jace
  • 1
  • 1
  • try `n > len(array) -1`. The maximum valid index is `len(array) - 1` – Z Li Jan 13 '21 at 22:06
  • Why do you have a list of selected numbers, where you put one number, just to read that same number in the next line? Why not just `return array[n] ** n`? – zvone Jan 13 '21 at 22:09
  • The code shown works fine except for the case where `n` is equal to the length of the array, or for negative values. Regarding the "equal" case this is essentially a typo: `>` should be `>=`. Alternately, we can use more sophisticated code to check negative indices as well. If there is any real question here, it's "what indices are valid?", for which I have linked a duplicate. – Karl Knechtel Jan 31 '23 at 01:45

3 Answers3

1

Here is a one liner:

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

Lior Cohen
  • 5,570
  • 2
  • 14
  • 30
0

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.

Ali Alnadous
  • 314
  • 2
  • 9
-1

Another one liner:

def index(array, n):
    return sum(array[n:n+1])**n or -1
Alver
  • 751
  • 5
  • 14