Calculate Fibonacci numbers up to at least n

2024/10/15 22:26:50

I am trying to make a function that allows a user to input a number and the result will be a list containing Fibonacci numbers up to the input and one above if the input is not in the series. For example, input of 4 will return [0, 1, 1, 2, 3, 5] but input of 3 would return [0, 1, 1, 2, 3]. I have managed to do this using the function below :

    def fibonacci(n):series = [0]if (n == 0):passelse:series.append(1)if (n == 1):passelse:while(series[len(series)-1] < n):newValue = series[len(series)-1] + series[len(series)-2]series.append(newValue)print(series)

However, I would now like to be able to do this recursively, any ideas?

Answer

A possible solution is the following

def fibo_up_to(n):if n < 2:return [1,1]else:L = fibo_up_to(n-1)if L[-1] < n:L.append(L[-1] + L[-2])return L

the idea is that to return the list of all fibonacci numbers less than n you can ask for the list of those less than n-1 and then possibly add just one element. This works from 2 on if we define the first two numbers being [1, 1]. Using [0, 1] instead creates a problem for 2 because a single next element is not enough.

This code is not inefficient on time (fibonacci is a double recursion, this is a simple recursion), but uses a lot of stack space.

https://en.xdnf.cn/q/117783.html

Related Q&A

IEC 62056-21, implement the protocol over a gsm connection

The protocol IEC 62056:21 tells us how to deal with enegy meters, its quite easy!The part where I am stuck is the implementation over a GSM data channel. Normally I would set things like:300 baudrate …

Cannot install plyfile in Anaconda

When u=i try to run the commandconda install plyfilein windows command promptFetching package metadata ...........PackageNotFoundError: Package not found: Package missing in current win-64 channels: -…

Expected singleton: stock.move - Odoo v9 community

Im creating a stock.picking from fleet_vehicle_log_services with this method:@api.multi def create_picking(self):self.ensure_one()vals = {move_lines: self.move_lines.id,origin: self.name}picking = self…

Python Kivy screen manager wiget scope

I am trying to control a screen manager from buttons in a separate class, but I cannot figure out what to set on the button on_press: statements.Kivy file:<HeaderSection>:anchor_x: centeranchor_y…

How do the async and await keywords work, exactly? Whats at the end of the await chain?

I have this code:async def foo(x):yield xyield x + 1async def intermediary(y):await foo(y)def bar():c = intermediary(5)What do I put in bar to get the 5 and the 6 out of c?Im asking because the asynci…

Serial port writing style

I am using two libraries to connect with a port, and two of them uses different styles in writing these commands. I want to understand the difference because I want to use the second one, but it result…

matplotlib plot to fill figure only with data points, no borders, labels, axes,

I am after an extreme form of matplotlibs tight layout. I would like the data points to fill the figure from edge to edge without leaving any borders and without titles, axes, ticks, labels or any othe…

Chromedriver: FileNotFoundError: [WinError 2] The system cannot find the file specified Error

Have looked for an answer, but couldnt find anything. It seems insistent on saying it cant find the file specified and then checks PATH, but cant see it even then :/ Ive put the directory in PATH: http…

Python - mutable default arguments to functions

I was going through https://docs.python.org/3.5/tutorial/controlflow.html#default-argument-values. I modified the example there a little bit as below:x = [4,5] def f(a, L=x):L.append(a)return Lx = [8,9…

Python: remove duplicate items from a list while iterating

I have a list named results, I want to get rid of the duplicate items in the list, the expected result and my results does not match, I checked my code but cannot find what is the problem, what happene…