Skip to content

Instantly share code, notes, and snippets.

@nicktimko
Last active August 29, 2015 14:16
Show Gist options
  • Save nicktimko/39a41948cff170ae7d0b to your computer and use it in GitHub Desktop.
Save nicktimko/39a41948cff170ae7d0b to your computer and use it in GitHub Desktop.
Linked List Fibonacci from DL
### Douglas Lewit is the author of this Python program. Written in Python 2.7.6.
### An example of using a linked list in Python to generate a Fibonacci sequence.
class Node:
def __init__(self, value, previous=None, next_=None):
self.value = value
self.previous = previous
self.next = next_
def __str__(self):
return format(self.value, ',')
class Fibonacci:
def __init__(self, firstTerm, secondTerm, lengthSequence):
self.firstTerm = Node(firstTerm)
self.secondTerm = Node(secondTerm, previous=self.firstTerm)
self.firstTerm.next = self.secondTerm
self.generate_fibo_list(lengthSequence)
def generate_fibo_list(self, terms):
current = self.secondTerm
for _ in range(terms - 1):
new = Node(current.value + current.previous.value, previous=current)
current.next = new
current = new
def __iter__(self):
current = self.firstTerm
while current.next:
yield current
current = current.next
first = raw_input("Enter the first term of your Fibonacci sequence: ")
first = int(first)
second = raw_input("Enter the second term of your Fibonacci sequence: ")
second = int(second)
length = raw_input("How many terms of the sequence do you want Python to compute? ")
length = int(length)
### Now create an instance of the Fibonacci class.
Fib = Fibonacci(first, second, length)
### Print out all the terms
for n, term in enumerate(Fib, start=1):
print('Term {: <2d}: {: >10s}'.format(n, term))
### I think Python rocks! Without a doubt Maple and Python are my favorite programming languages!!!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment