0

I write a function to find n'th fibonancci . Codes here -

def fib(n):
    res1 = 0
    res2 = 0
    for i in str(n):
        res1 = n - 1
        for j in str(n):
            res2 = n - 2
    return res1 + res2

Through the above code, if i enter n = 4 than it prints 5. Thats correct. But if i print n = 5 than it prints 7, it's not correct. How to fix the bugs here. Is there any logical error? Can anyone explain in details.

Don't use recursive method I want it to do with iteration.

Yedhu Krishnan
  • 1,225
  • 15
  • 31
Tanzir Uddin
  • 51
  • 1
  • 9

1 Answers1

1
def fib(n):
    a,b = 1,1
    for i in range(n-1):
        a,b = b,a+b
    return a

print(fib(4))

Well, there is a TechnoBeans page showing you 5 Ways of Fibonacci in Python.

Your code:

def fib(n):
    res1 = 0
    res2 = 0
    for i in str(n):     # i gets the string value 9 here
        res1 = n-1       # res1 is 9-1 which is 8
        for j in str(n): # j gets the string value 9 here
            res2= n -2   # res2 is 9-2 which is 7 
    return res1 +res2    # returns 8 + 7 which is 15

print(fib(9))            # output 15

You have a lot of unnecessary things in your code, you first need some basic understanding of Python. I personally found the following site very helpful to learn Python: Learn Python The Hard Way

To understand why your code doesn't do Fibonacci you need to understand how Fibonacci works. You can read more about Fibonacci at Fibonacci Sequence on Math Is Fun site.

Wolf
  • 9,679
  • 7
  • 62
  • 108
  • 1
    @Tristan If you use *this* and *here* for links, then there is no chance to recover it if the contents moves (got archived). @Do0msDay *`To understand why your code doesn't do Fibonacci`* - I don't think so, some basic python understanding isn't negligible. – Wolf Jun 02 '16 at 08:17
  • @Wolf I agree, he has alot of unnecessary things in his code. I was not sure how to approach it. –  Jun 02 '16 at 08:22
  • 1
    I tried my best to integrate the page titles (this is often what you google for) in a readable manner. I hope you appreciate my changes :) – Wolf Jun 02 '16 at 09:00
  • @Wolf Ah, I see thanks! –  Jun 02 '16 at 09:59