简体   繁体   中英

python using the fibonacci sequence

I am trying to only have the words print out if they occur the same number of times as in the fibonacci sequence. If a words show up 1,2,3,5,8 etc then it will print up. I have gotten the program to print up the words based on how many times the appear. I am having trouble figuring out how to use the sequence in my program. Any tips or examples would be very appreciated.

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

You can tack this onto the end:

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]

You'll have to import * from math beforehand, as I'm using the closed-form function for the nth Fibonacci number.

Here's an approach that you could use that minimizes impact on existing code.

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]))

But it might make more sense to to make a set of fibonacci numbers before reading the file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM