-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

上記のコードは、問題に対する私の試みです。ただし、次のように返されます。

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

したがって、コードの n**b 部分に問題があります。

4

2 に答える 2

3

リスト内包表記の使用に興味があるかもしれませんが、これらは通常、自分でリストをループするよりも効率的です。また、アイテムの代わりに繰り返し処理していたリストを使用しています。

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)]
于 2013-10-29T10:54:34.823 に答える
2

それ以外の

a.append(n**b)

使用する

a.append(n**i)

map()または、次の関数を使用することもできます。

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

浮動小数点演算を使用していない場合 (または、丸めによって生じる不正確さを気にしない場合) は、インクリメンタル アプローチ ( n^k = n^(k-1) * n) を使用することもできます。n log n、これは線形になります)。

于 2013-10-29T10:51:54.630 に答える