查找列表中的模式的周期

时间:2016-04-26 19:35:23

标签: python intervals fibonacci period

我对编码比较新,但我看到一个很棒的episode of Numberphile,他们使用Fibonacci序列模数的特定重复模式来为结果数分配音调。这是一个很好的小实验来测试我的知识!

因此,我能够创建一个简单的循环来创建Fibonacci序列列表,并创建另一个函数来计算除以n后生成序列的剩余部分。但是在模数列表中找到模式的周期被证明是困难的。

这是我到目前为止所拥有的:

#Fibonacci.py
#Basic terms
fiblist = list()
inp = "> "
n=None

#Calculates the FIbonacci sequence
def fib(n):
    a,b = 0,1
    while True:
        try:
            print "How many terms? "
            n = int(raw_input(inp))
            if n <= 0:
                print "Please enter a positive integer."
                continue
            else:
                for i in range(0,n):
                    a,b = b, a + b
                    fiblist.append(a)
                break
        except ValueError:
            print "Please enter a positive integer, not a letter or symbol"
            continue    
    return fiblist

#Calculates the modulo of each integer in fiblist
def modulo(n):  
    print """
Do you want to find the modulo?
1. Yes
2. No"""
    choice = raw_input(inp)
    if choice =="1":
        modlist = list()
        print "What modulo do you want to use?"
        modx = int(raw_input(inp))
        modlist = [x % modx for x in fiblist]
        print modlist
        print "The period of the pattern is ", principal_period(modlist)
        print "Goodbye!"
    else: 
        print "Goodbye!"

#Calculates the period of the modulo pattern of the Fibonacci sequence
def principal_period(modlist):
    a = str(modlist)
    i = (a+a).find(a, 1, -1)
    return None if i == -1 else n[:i]

print fib(n)
modulo(n)

失败的部分是

def principal_period(modlist):
    a = str(modlist)
    i = (a+a).find(a, 1, -1)
    return None if i == -1 else n[:i]

总是返回&#34;无&#34;我从帖子over here得到了关于答案的内容。老实说,我不太理解这个答案,也没有给我预期的结果。

您对计算给定列表中重复模式的周期有什么建议吗?

2 个答案:

答案 0 :(得分:0)

它失败了,因为modlist是一个整数列表,而不是字符串。更改principal_period中的第二行和第四行,如下所示:

def principal_period(modlist):
    a = ''.join(str(m) for m in modlist)
    i = (a+a).find(a, 1, -1)
    return None if i == -1 else a[:i]

您需要将数字加入长字符串,而不是str(modlist),并且最后一行有{#1}}而不是n[:i]

现在运行此程序会显示:

a[:i]

这个输出的有趣之处在于Fibonacci数字遵循奇数,奇数,偶数序列。试试99个条款!

答案 1 :(得分:0)

这是找到离散函数周期的简单算法:

def findperiod(f, minlength=1, repetitions=2):
    """Find the period of a function f.

    Idea: assume length i = 1. Check that second copy is same as first (j
    iteration). If not, assume length 2. And so on. Once second copy matches
    first (no j breaks), return assumed length.

    The optional repetitions argument can be increased to check for more
    repetitions than the default 2 (two copies of the same sequence at the start
    of the list).

    Returns None if not enough repetitions are found in first billionish values.
    """
    for i in (range(minlength, 2**30)):
        for rep in range(1, repetitions):
            for j in range(i):
                if f(j) != f(i*rep+j): break
            else: return i

如果函数的计算成本很高,则记住是一个好主意。我在这里没有这样做,因为如果不需要的话,它会占用很多内存。