python使用斐波纳契数列

时间:2011-04-14 20:00:46

标签: 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')

3 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:0)

你可以将其解决到最后:

frequencies = sorted(word_freq.items(), key=lambda item: item[1])

def fib2(n):
  phi = (1.0 + sqrt(5)) / 2.0

  return (phi**n - (1 - phi)**n) / (sqrt(5))

for word in frequencies:
  n = 0

  while word[1] < fib2(n):
    n += 1

  if word[1] == fib2(n):
    print word[0]

您必须事先import * from math,因为我正在使用nth斐波纳契数的闭合函数。

答案 2 :(得分:0)

这是一种可以使用的方法,可以最大限度地减少对现有代码的影响。

import itertools

...


items = [item for item in word_freq.items() if 
                 item[1] in itertools.takewhile(lambda f: f <= item[1], fib())]
print(sorted(items, key=lambda item: item[1]))

但是在阅读文件之前制作一组斐波那契数字可能更有意义。