簡體   English   中英

使用斐波那契序列的python

[英]python using the fibonacci sequence

我試圖僅將單詞打印出來的次數與斐波那契數列中出現的次數相同。 如果一個單詞出現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]

您必須事先import * from mathimport * from math ,因為我正在使用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]))

但是在讀取文件之前先制作一組斐波那契數字可能更有意義。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM