如何在numpy.nditer中指定开始和步长?

2024-10-04 11:22:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下Python代码,用于计算第一个nEuler Totient函数值:

import numpy as np

def euler_totients(n):
    phi = np.arange(n+1)

    it = np.nditer(phi, flags=['f_index'])
    for i in it:
        if i == it.index and it.index > 1:
            for j in range(it.index, n+1, it.index):
                phi[j] -= phi[j] / it.index

    return phi

我想将numpy.nditer用于内部循环,但它似乎不允许指定内部循环所需的起点或步长。官方的documentation for ^{}包含了对itershape参数的简要描述(听起来很有希望),但它有点模糊,没有包含示例

那么,有没有一种方法可以指定numpy.nditer的起点和步长,如果有,如何指定


Tags: 函数代码inimportnumpyforindexnp
1条回答
网友
1楼 · 发布于 2024-10-04 11:22:38

纯python版本更快:

In [166]: def foo(n):
     ...:     phi = list(range(n+1))
     ...:     for index,i in enumerate(phi):
     ...:        if i==index and index>1:
     ...:            for j in range(index, n+1, index):
     ...:               phi[j] -= int(phi[j]/index)
     ...:     return phi
     ...: 
In [167]: foo(10)
Out[167]: [0, 1, 1, 2, 2, 4, 2, 6, 4, 6, 4]
In [168]: timeit euler_totients(1000)
15.7 ms ± 63.4 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
In [169]: timeit foo(1000)   
637 µs ± 24.5 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

相关问题 更多 >