python 使用斐波那契数列

标签 python

我试图仅在单词出现的次数与斐波那契数列中出现的次数相同时才打印出来。如果一个单词显示 1、2、3、5、8 等,那么它就会打印出来。我已经让程序根据出现的次数打印单词。我无法弄清楚如何在程序中使用该序列。任何提示或示例将不胜感激。

def fib():
    a,b = 0, 1
    while 1:
            yield a
            a, b= b, a+b

from collections import Counter 
import string


while True:
    filename=raw_input('Enter a file name: ')
    if filename == 'exit':
        break
    try:
        file = open(filename, 'r') 
        text=file.read() 
        file.close() 
    except:
        print('file does not exist')
    else:

        for word in string.punctuation:
            text=text.replace(word, "")
        word_list = text.lower().split(None)
        word_freq = {}

        for word in word_list:
            if len(word) > 1:
                word_freq[word] = word_freq.get(word, 0) + 1

        print(sorted(word_freq.items(), key=lambda item: item[1])) 
// I am pretty sure something with the seqeunce should go into the above line
// but have been unable to figure it out.         

print('Bye')

最佳答案

class FibSet:
    '''Fibonacci sequence with the in operator defined'''

    def __init__(self):
        self.a, self.b = 0, 1
        self.fib = set()

    def __contains__(self, n):
        if n > self.b:
            self.compute_upto(n)
        return n in self.fib

    def compute_upto(self, n):
        while self.b < n:
            self.fib.add(self.a)
            self.a, self.b = self.b, self.a + self.b

关于python 使用斐波那契数列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5668969/

相关文章:

模拟模式下的Python代码

python - 当我在 PyQt4 中打开新窗口时如何关闭旧窗口

python - 您如何将十进制数拆分为小数点以获得分钟和秒? Python

Python selenium send_keys 不工作无法设置登录字段

python - 编写好的 Python 代码的技巧

python if-elif-else 总是转到 else

python - Windows 没有将命令行参数传递给从 shell 执行的 Python 程序

javascript - 使用安全 WebSocket 连接的 Django channel - WSS ://

python - 判断对象是否已经完成

python - python 动态构造实例