这是在Python中生成ThueMorse序列的有效方法吗?

2024-06-01 23:05:12 发布

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

使用下面代码中的生成器是在Python中生成Thue-Morse sequence的有效方法吗?在

# generate the Thue-Morse sequence
def genThueMorse():
    # initialize
    tms = '0'
    curr = 0
    while True:
        # generate next sequence
        if curr == len(tms):
            tmp = ''
            for i in range(len(tms)):
                if tms[i] is '0':
                    tmp += '1'
                else:
                    tmp += '0'
            tms += tmp
        yield tms[curr]
        curr +=1

下面是测试它的代码:

^{pr2}$

Tags: the方法代码morselenifdeftmp
3条回答

我认为发电机的效率相当高。我想要这样的东西:

from itertools import count, izip

def genThueMorse():
    tms = [0]
    invert = [1, 0]
    for tm, curr in izip(tms, count()):
        yield str(tm)
        if curr == len(tms) - 1:
            tms += [invert[c] for c in tms]

这很简洁,是不是“高效”?在

import itertools

def genThueMorse():
    for n in itertools.count():
        yield (1 if bin(n).count('1')%2 else 0)

帮助补充其他答案:如果您只想计算序列中的第n位,请使用:

lambda n: bin(n).count("1") % 2

或者,如果喜欢函数:

def calculate_nth(n):
  return bin(n).count("1") % 2

示例:

^{pr2}$

这可以用序列:0110 1 0 0 1 1 001 0 1 1 0进行验证

相关问题 更多 >