【问题标题】:Is this an efficient way to generate the Thue-Morse sequence in Python?这是在 Python 中生成 Thue-Morse 序列的有效方法吗?
【发布时间】:2014-09-27 15:42:39
【问题描述】:

使用下面代码中的生成器是在 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

这是测试它的代码:

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

【问题讨论】:

    标签: python generator


    【解决方案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

    【讨论】:

      【解决方案2】:

      这样简洁,是不是“高效”?

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

      【讨论】:

      • 这完全是正确的想法;封闭形式的表示避免了将整个序列迄今为止存储在生成器中的需要(这使得生成器本身看起来很傻)。至于如何实际计算位数,另请参阅:stackoverflow.com/questions/9829578/…
      • 不错。没有使用额外的内存。然后问题转移到计数位的快速方法。 stackoverflow.com/questions/9829578/…
      • Re: yield (1 if bin(n).count('1')%2 else 0) -- 因为bin(n).count('1') % 2在你返回1时为1,在你返回0时为0,你应该可以这样写代码:yield bin(n).count('1') % 2。也许你的方式更明确地返回 1 或 0。
      • @hughdbrown:好点。我不记得我当时在想什么,所以我不能说我故意这样写是为了更明确,尽管它是。删除if/else .. 肯定会提高效率
      【解决方案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]
      

      【讨论】:

      • 为什么不把counter = count(); while True: curr = counter.next()改成for curr in count():
      • @icktoofay:好主意。我最初以为这样的循环会在 0 处停止。
      猜你喜欢
      • 1970-01-01
      • 2011-11-24
      • 1970-01-01
      • 1970-01-01
      • 2011-08-12
      • 2011-10-01
      • 2012-01-06
      • 1970-01-01
      • 2012-03-27
      相关资源
      最近更新 更多