在Python中生成Thue-Morse序列的高效方法吗?
在下面的代码中,使用生成器生成 Thue-Morse序列,这样做是否高效呢?
# 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
这里有一段代码可以用来测试:
tms = koch.genThueMorse()
while True:
print(next(tms))
3 个回答
1
为了补充其他答案,如果你只想计算序列中的第n个数字,可以使用:
lambda n: bin(n).count("1") % 2
或者如果你更喜欢用一个函数:
def calculate_nth(n):
return bin(n).count("1") % 2
例子:
f = lambda n: bin(n).count("1") % 2
f(0) # This will return 0
f(1) # This will return 1
f(2) # This will return 1
...
f(10) # This will return 0
你可以用这个序列来验证:0 1 1 0 1 0 0 1 1 0 0 1 0 1 1 0
1
我觉得使用生成器会比较高效。我会选择类似这样的方式:
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]
3
这个写法简洁,是不是“高效”的呢?
import itertools
def genThueMorse():
for n in itertools.count():
yield (1 if bin(n).count('1')%2 else 0)