Javascript到Python,在for循环的条件和最终表达式中按位移位

时间:2017-05-20 02:42:22

标签: javascript python for-loop bitwise-operators bit-shift

我有一个用javascript编写的FFT代码,粘贴在下面:

function FFT(re, im) {
        var N = re.length;
        for (var i = 0; i < N; i++) {
            for (var j = 0, h = i, k = N; k >>= 1; h >>= 1)
                j = (j << 1) | (h & 1);
            if (j > i) {
                re[j] = [re[i], re[i] = re[j]][0];
                im[j] = [im[i], im[i] = im[j]][0]
            }
        }

        for (var hN = 1; hN * 2 <= N; hN *= 2)
            for (i = 0; i < N; i += hN * 2)
                for (j = i; j < i + hN; j++) {
                    var cos = Math.cos(Math.PI * (j - i) / hN),
                        sin = Math.sin(Math.PI * (j - i) / hN);
                    var tre = re[j + hN] * cos + im[j + hN] * sin,
                        tim = -re[j + hN] * sin + im[j + hN] * cos;
                    re[j + hN] = re[j] - tre;
                    im[j + hN] = im[j] - tim;
                    re[j] += tre;
                    im[j] += tim;
                }
    }

for循环中有一个语句

for (var j = 0, h = i, k = N; k >>= 1; h >>= 1)

我想知道如何在Python中编写这个for循环? k s数组和h数组对我来说不是很清楚,所以我不知道如何使用zip

2 个答案:

答案 0 :(得分:1)

一种可能的方法是使用while循环:

j = 0
h = i
k = N >> 1
while k > 0:
    ... # current logic in the for loop
    k >>= 1
    h >>= 1

答案 1 :(得分:1)

@ fileyfood500描述了最简单的方法。

另一种方法可能是分离出生成器中的kh逻辑,并使用for循环:

def gen(k, h):
    while k >> 1:
        yield h
        h >>= 1
        k >>= 1

for i in range(N):
    j = 0
    for h in gen(N, i):
        j = (j << 1) | (h & 1)

如果你这样做,你可以reduce循环:

from functools import reduce    # Py3

for i in range(N):
    j = reduce(lambda j, h: (j << 1) | (h & 1), gen(N, i), 0)