这是在Python中生成Thue-Morse序列的有效方法吗? [英] Is this an efficient way to generate the Thue-Morse sequence in Python?

查看:136
本文介绍了这是在Python中生成Thue-Morse序列的有效方法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正在使用下面的代码中的生成器,这是生成的有效方法Python中的Thue-Morse序列?

Is using a generator as in the code below, an efficient way to generate the Thue-Morse sequence in Python?

# 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

以下是对其进行测试的代码:

Here is code to test it:

tms = koch.genThueMorse()
while True:
   print(next(tms))

推荐答案

这很简洁,是否有效"?

This is concise, is it "efficient"?

import itertools

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

这篇关于这是在Python中生成Thue-Morse序列的有效方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆