微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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
    ,您可以将其固定到最后:
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]
您必须事先将ѭ3,,因为我正在对
nth
斐波那契数使用封闭形式的函数。     ,您可以使用以下方法来最大程度地减少对现有代码的影响。
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]))
但是在读取文件之前先制作一组斐波那契数字可能更有意义。     

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。