Last active
August 29, 2015 14:16
-
-
Save nicktimko/39a41948cff170ae7d0b to your computer and use it in GitHub Desktop.
Linked List Fibonacci from DL
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
### 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