Skip to content Skip to sidebar Skip to footer

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 g

Solution 1:

classFibSet:
    '''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

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

Solution 2:

You can tack this onto the end:

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

deffib2(n):
  phi = (1.0 + sqrt(5)) / 2.0return (phi**n - (1 - phi)**n) / (sqrt(5))

for word in frequencies:
  n = 0while word[1] < fib2(n):
    n += 1if 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.

Solution 3:

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.

Post a Comment for "Python Using The Fibonacci Sequence"