Detect period of unknown source

前端 未结 4 921
粉色の甜心
粉色の甜心 2020-12-28 23:43

How to detect repeating digits in an infinite sequence? I tried Floyd & Brent detection algorithm but come to nothing... I have a generator that yields

4条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-29 00:13

    I have no idea about proper algorithms to apply here, but my understanding also is that you can never know for sure that you've detected a period if you have consumed only a finite number of terms. Anyway, here's what I've come up with, this is a very naive implementation, more to educate from the comments than to provide a good solution (I guess).

    def guess_period(source, minlen=1, maxlen=100, trials=100):
        for n in range(minlen, maxlen+1):
            p = [j for i, j in zip(range(n), source)]
            if all([j for i, j in zip(range(n), source)] == p
                   for k in range(trials)):
                return tuple(p)
        return None
    

    This one, however, "forgets" the initial order and returns a tuple that is a cyclic permutation of the actual period:

    In [101]: guess_period(gen)
    Out[101]: (0, 1, 4, 8, 2, 1, 3, 3, 1, 1)
    

    To compensate for this, you'll need to keep track of the offset.

提交回复
热议问题