Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Unable to print fibonacci sequence

I am working on a python tutorial. I am getting an incorrect result as I try to work through an example.

This question: AttributeError: 'int' object has no attribute 'append'

does not answer my question.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I have defined my function like so:

def fibonaccci(sequence_length):
    "Return the Fibonacci sequene of length * sequence_length"
    sequence = [0,1]
    if sequence_length < 1:
        print("Fibonacci squence only defined fo length 1 or greater")
        return
    if 0 < sequence_length < 3:
        return sequence[:sequence_length]
    for i in range(2, sequence_length):
        sequence_length.append(sequence[i-1]+sequence[i-2])
    return sequence

Any help understanding what this issue is would be greatly appreciated.

Expected:

[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]

Actual:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
/tmp/ipykernel_35261/4107038898.py in <module>
----> 1 fibonaccci(int(12))

/tmp/ipykernel_35261/2532562687.py in fibonaccci(sequence_length)
      8         return sequence[:sequence_length]
      9     for i in range(2, sequence_length):
---> 10         sequence_length.append(sequence[i-1]+sequence[i-2])
     11     return sequence

AttributeError: 'int' object has no attribute 'append'

>Solution :

You’re trying to append to the int parameter sequence_length instead of the length sequence. Just append to that instead:

def fibonaccci(sequence_length):
    "Return the Fibonacci sequene of length sequence_length"
    sequence = [0, 1]
    if sequence_length < 1:
        print("Fibonacci squence only defined for length 1 or greater")
        return
    if 0 < sequence_length < 3:
        return sequence[:sequence_length]
    for i in range(2, sequence_length):
        sequence.append(sequence[i - 1] + sequence[i - 2])
    return sequence
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading