views:

5771

answers:

9

Updated: EDIT! I have coded the program wrongly. Instead of returning the Fibonacci numbers between a range (ie. startNumber 1, endNumber 20 should = only those numbers between 1 & 20), I have written for the program to display all Fibonacci numbers between a range (ie. startNumber 1, endNumber 20 displays = First 20 Fibonacci numbers). I thought I had a sure-fire code. I also do not see why this is happening.

startNumber = int(raw_input("Enter the start number here "))
endNumber = int(raw_input("Enter the end number here "))

def fib(n):
    if n < 2:
        return n
    return fib(n-2) + fib(n-1)

print map(fib, range(startNumber, endNumber))

Someone pointed out in my Part II (which was closed for being a duplicate - http://stackoverflow.com/questions/504193/how-to-write-the-fibonacci-sequence-in-python-part-ii) that I need to pass the startNumber and endNumber through a generator using a while loop. Can someone please point me in the direction on how to do this? Any help is welcome.

Thank you.



Old: Hey there,

I'm a learning programmer and I've run into a bit of a jumble. I am asked to write a program that will compute and display Fibonacci's Sequence by a user inputted start number and end number (ie. startNumber = 20 endNumber = 100 and it will display only the numbers between that range). The trick is to use it inclusively (which I do not know how to do in Python? - I'm assuming this means to use an inclusive range?).

What I have so far is no actual coding but rather:

  • Write Fib sequence formula to infinite
  • Display startNumber to endNumber only from Fib sequence.

I have no idea where to start and I am asking for ideas or insight into how to write this. I also have tried to write the Fib sequence forumla but I get lost on that as well.

Thank you for the help. I will be participating actively in this question and will appreciate ANY help.

A: 

Calculate the Fibonacci sequence from the beginning (presumably using a while loop), but don't output anything until the values are >= startNumber, and exit as soon as the values are greater than endNumber.

Actual code isn't provided because this smells like homework, but it sounds from your wording that bounding the output is the part that you were uncertain about.

Charles Duffy
Ah. A while loop is exactly what I was looking for but I wouldn't know how to combine a while loop with the startNumber and endNumber.I'm actually not a student but I am doing this based off a mentor-merit. I'm trying to learn this language to help me get a job really.Thank you for the reply
SD
+4  A: 

You can get a good start point here:

You have enough material there, a recursive approach, an iterative approach, the Binet's formula and some techniques for computing large individual Fibonacci numbers...

CMS
Thank you. I will look into this.
SD
+1  A: 

You must be joking or this is a homework problem? The Fibonacci function is discussed in the Python tutorial.

Jeff Bauer
This is not a joke, sorry. I do need assistance and asked for it. Sorry.
SD
I have looked through the python.org tutorial (and used the search function) and cannot find mention of the Fibonacci sequence. Care to point to it? I see examples uses fib() but nothing about Fibonacci's sequence.
SD
here is the definition of the fibonacci-sequence function: http://docs.python.org/tutorial/controlflow.html#defining-functions
hop
+1 for mentioning the tutorial, even if it would have been nicer to include the link to it.
Paul Wagland
A: 

Start from reading good Python book. One of such book is "How to Think Like a Computer Scientist", especially chapter 5 in your case.

Michał Niklas
Just got a .pdf version of it, thank you.
SD
A: 

this was asked in general take a look

here is the python implementation

this is the question

Oscar Cabrero
+11  A: 

The idea behind the Fibonacci sequence is shown in the following Python code:

def fib(n):
   if n == 1:
      return 1
   elif n == 0:   
      return 0            
   else:                      
      return fib(n-1) + fib(n-2)

This means that fib is a function that can do one of three things. It defines fib(1) == 1, fib(0) == 0, and fib(n) to be:

fib(n-1) + fib(n-2)

Where n is an arbitrary integer. This means that fib(2) for example, expands out to the following arithmetic:

fib(2) = fib(1) + fib(0)
fib(1) = 1
fib(0) = 0
# Therefore by substitution:
fib(2) = 1 + 0
fib(2) = 1

We can calculate fib(3) the same way with the arithmetic shown below:

fib(3) = fib(2) + fib(1)
fib(2) = fib(1) + fib(0)
fib(2) = 1
fib(1) = 1
fib(0) = 0
# Therefore by substitution:
fib(3) = 1 + 1 + 0

The important thing to realize here is that fib(3) can't be calculated without calculating fib(2), which is calculated by knowing the definitions of fib(1) and fib(0). Having a function call itself like the fibonacci function does is called recursion, and it's an important topic in programming.

This sounds like a homework assignment so I'm not going to do the start/end part for you. Python is a wonderfully expressive language for this though, so this should make sense if you understand math, and will hopefully teach you about recursion. Good luck!

Edit: One potential criticism of my code is that it doesn't use the super-handy Python function yield, which makes the fib(n) function a lot shorter. My example is a little bit more generic though, since not a lot of languages outside Python actually have yield.

James Thompson
This is not a homework problem but wow thank you for the answer! I understand what I need to do but starting it and implementing is what I am stuck on now (especially with implementing user input values). Can you provide some insight into this? I keep getting a <function fib at 0x0141FAF0> error.
SD
I understand that you're trying very hard to implement a program that may be beyond your current ability. Having me write more code will not help you. You should try to hack around with my code until it works, and read more Python tutorials. Whitespace may be a problem, but I don't know that error.
James Thompson
I understand. Is there any other idea that you think I may be missing? I understand if you cannot help however. I thank you for your time.
SD
Your <function fib at 0x0141FAF0> error may be the result of saying "fib" (which refers to the function itself) instead of "fib()" which will call the function. Best of luck.
Kiv
Bear in mind that this naive recursive method of calculating Fibonacci numbers can get into stack overflow (not the site) real fast. For practical purposes, generate iteratively or use some sort of memoization or something.
David Thornley
A: 

Go find out how to convert a recursive problem into an iterative one. Should be able to calculate from there.

That's might be the principles that they're trying to get you to learn, especially if this is an Algorithms course.

Calyth
+1  A: 

I think the most productive thing you can do will be to write some code. ANY code. If you can't get it to work, edit it into your original question along with the error you're getting, and we'll try to guide you toward getting that particular snippet of code to work. That should get you started.

Jorenko
+9  A: 

There are lots of information about the Fibonacci Sequence on wikipedia and on wolfram. A lot more than you may need. Anyway it is a good thing to learn how to use these resource to find (quickly if possible) what you need.

Write Fib sequence formula to infinite

In math it's given in a recursive form:

fibonacci from wikipedia

In programming infinite doesn't exists. You can use a recursive form translating the math form directly in your language, for example in python it becomes:

def F(n):
    if n == 0: return 0
    elif n == 1: return 1
    else: return f(n-1)+f(n-2)

Try it in your favourite language and see this form requires a lot of memory as n gets bigger.

Go on on the sites I linked to you and will see this (on wolfram):

alt text

This one is pretty easy to implement and very, very fast to compute, in Python:

def F(n):
    return ((1+sqrt(5))**n-(1-sqrt(5))**n)/(2**n*sqrt(5))

An other way to do it is following the definition (from wikipedia):

The first number of the sequence is 0, the second number is 1, and each subsequent number is equal to the sum of the previous two numbers of the sequence itself, yielding the sequence 0, 1, 1, 2, 3, 5, 8, etc.

If your language supports iterators you may do something like:

def F():
    a,b = 0,1
    yield a
    yield b
    while True:
        a,b = b,a+b
        yield b

Display startNumber to endNumber only from Fib sequence.

Once you know how to generate Fibonacci Numbers you just have to cycle trough the numbers and check if they verify the given conditions.

Suppose now you wrote a f(n) that returns the n-th term of the Fibonacci Sequence (like the one with sqrt(5) )

In most languages you can do something like:

def SubFib(startNumber, endNumber):
    n = 0
    cur = f(n)
    while cur<=endNumber:
        if startNumber <= cur:
            print cur
        n += 1
        cur = f(n)

In python I'd use the iterator form and go for:

def SubFib(startNumber, endNumber):
    for cur in F():
        if cur>endNumber: return
        if cur>=startNumber:
            yield cur

for i in SubFib(10, 200):
    print i

My hint is to learn to read what you need. Project Euler (google for it) will train you to do so :P Good luck and have fun!

Andrea Ambu
Thank you very much for the help! Thanks to you I figured it out! I also started another question regarding this assignment for me: http://stackoverflow.com/questions/504193/how-to-write-the-fibonacci-sequence-in-python-part-iiCheck it out if you have time. ;)
SD
I commented it :)
Andrea Ambu
Thanks Andrea - I figured out that problem! I did not know about the differences of calling the [] in the range function. I also have a new problem I've ran into. Please look into it if you have the time. Thank you.
SD
It's up top. Under Updated.
SD
You need to use a while loop, not map. Try to figure it out on your own, then come back with the code if you can't do it. I'm not lazy (the code is shorter than this comment). I'm doing that for you, try it out with the "while" hint ;) If you have problem with that come back again ;)
Andrea Ambu
I'm back, lol. I got rid of the map(range) function and am using only a range(startNumber, endNumber) function. Now the problem I have is where to use the while statement. I try at the beginning of the function but of course there is a billin an done lines of error. Where should I be putting it? Thx
SD
Try to do, by hand, an example of input-output of your program (with a short range). Try then to figure out where your program is wrong. Try to convert the "by-hand method" in code. This is for exercise, to learn. I could put down two lines of code but I don't think you'll learn anything from them.
Andrea Ambu
I wrote out a psuedocode and wrote it out but I still cannot get it to work :(. I either get an error that says fib function at randomnumbershere or it doesn't compute it the way I want (will only compute by displaying nth Fibonacci numbers not between a range. Hmmm.
SD
... did you read my post? I mean, what's wrong with the SubFib function?
Andrea Ambu
I'm not using your code, see my code posted above. I'm going to give this one more go tonight, I'll reply with anoter comment. Thank you for keeping up with this bro - I really appreciate it.
SD
You welcome :) I don't really understand now what you really want to be your output :O
Andrea Ambu
I still can't get it bro. :(. Do you have an Instant Messenger? http://www2.bakersfieldcollege.edu/cs/pwhitney/privdocs/coms_b10/COMS%20B10%20Assignment%2003%20(fibonacci%20sequence).pdf Here is a link to the assignment. I think I need to approach it entirely differently.
SD
In my post there is all you need. Give me your skype if you want.
Andrea Ambu
My Skype ID is HavocSD
SD
Hey bro - just wanted to let you know that I figured out a way to do it without yields, returns or even defining my own function. Let me know if you'd like to see the code.
SD