-1
def powers(n, k):
    """Compute and returns the indices numbers of n, up to and including n^k"""
    b = range(k+1)
    print b
    a = []
    for i in b:
        print a  
        a.append(n**b)
    return a

The above code is my attempt at the problem. However it returns:

TypeError: unsupported operand type(s) for ** or pow(): 'int' and 'list'

So there is some problem with the n**b part of my code.

lvc
  • 34,233
  • 10
  • 73
  • 98
  • 1
    Please indent your code and also add the code that calls `powers` so we can see what the input `n` and `k` are – YXD Oct 29 '13 at 10:52

2 Answers2

3

You might be interested in using list comprehension, these are usually more eficient than looping through a list yourself. Also, you we're using the list your were iterating over instead of the item.

def powers(n, k):
    """Compute and returns the indices numbers of n, up to and including n^k"""
    return [n**i for i in range(k+1)]
Exelian
  • 5,749
  • 1
  • 30
  • 49
  • Using ```xrange``` instead of ```range``` can improve the efficiency a bit. – Danstahr Oct 29 '13 at 11:28
  • `xrange` does provide some benefit, but mostly just for very large lists. As one probably doesn't want to compute very large powers using this function (k>100) there isn't too much benefit to using it. – Exelian Oct 29 '13 at 12:17
2

Instead of

a.append(n**b)

use

a.append(n**i)

Or you can simply use the map() function:

base = 10
lst = xrange(10)
result = map(lambda x: base**x, lst) # 10^0 to 10^9

If you're not working with floating point arithmetics (or you don't care about imprecisions introduced by rounding), you could also use incremental approach (n^k = n^(k-1) * n), which could be a bit faster for large arrays (while the algorithms above usually compute in n log n, this one would be linear).

Danstahr
  • 4,190
  • 22
  • 38