检测未知来源的期间

发布于 2021-01-29 15:12:58

如何检测无限序列中的重复数字?我尝试了 Floyd&Brent
检测算法,但一无所获…我有一个生成器,其生成的数字范围为0到9(含0)(包括0),并且我必须识别其中的一个句点。

示例测试用例:

import itertools

# of course this is a fake one just to offer an example
def source():
    return itertools.cycle((1, 0, 1, 4, 8, 2, 1, 3, 3, 1))

>>> gen = source()
>>> period(gen)
(1, 0, 1, 4, 8, 2, 1, 3, 3, 1)
关注者
0
被浏览
49
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    经验方法

    这是一个有趣的问题。您问题的更一般形式是:

    给定长度未知的重复序列,请确定信号的周期。

    确定重复频率的过程称为傅里叶变换。在您的示例中,信号是干净且离散的,但是以下解决方案即使在连续的噪声数据下也可以使用!该FFT将尝试通过在所谓的“波空间”或“傅立叶空间”接近他们复制的输入信号的频率。基本上,该空间中的峰值对应于重复信号。信号的周期与峰值的最长波长有关。

    import itertools
    
    # of course this is a fake one just to offer an example
    def source():
        return itertools.cycle((1, 0, 1, 4, 8, 2, 1, 3, 3, 2))
    
    import pylab as plt
    import numpy as np
    import scipy as sp
    
    # Generate some test data, i.e. our "observations" of the signal
    N = 300
    vals = source()
    X = np.array([vals.next() for _ in xrange(N)])
    
    # Compute the FFT
    W    = np.fft.fft(X)
    freq = np.fft.fftfreq(N,1)
    
    # Look for the longest signal that is "loud"
    threshold = 10**2
    idx = np.where(abs(W)>threshold)[0][-1]
    
    max_f = abs(freq[idx])
    print "Period estimate: ", 1/max_f
    

    这为这种情况提供了正确的答案,10尽管如果N不对周期进行清楚的划分,您将获得一个接近的估计。我们可以通过以下方式将其可视化:

    plt.subplot(211)
    plt.scatter([max_f,], [np.abs(W[idx]),], s=100,color='r')
    plt.plot(freq[:N/2], abs(W[:N/2]))
    plt.xlabel(r"$f$")
    
    plt.subplot(212)
    plt.plot(1.0/freq[:N/2], abs(W[:N/2]))
    plt.scatter([1/max_f,], [np.abs(W[idx]),], s=100,color='r')
    plt.xlabel(r"$1/f$")
    plt.xlim(0,20)
    
    plt.show()
    

    在此处输入图片说明



知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看