Return the Fibonnaci elements from the last term to the first [duplicate]

0

I've returned some specific elements already, but I'm trying to get back to the first one. In the code below did I return a certain element, how do I now create from the first, to the fifth, to the tenth?

def element( f )
        return  f  if f <= 1
        element( f - 1 ) + element( f - 2 )
    end
    
asked by anonymous 16.10.2018 / 03:05

2 answers

1

By the description you want to return a list and not the final term, then you must manipulate the returns with lists, something like this:

def fibonacci(termo)
    return [] if termo == 0
    return [0] if termo == 1
    return [0, 1] if termo == 2 
    lista = fibonacci(termo - 1) 
    lista << lista[-2] + lista[-1]
    return lista
end
print fibonacci(10)

See running on ideone . And no Coding Ground . Also put it in GitHub for future reference .

    
16.10.2018 / 03:57
0

I did as Maniero said, I just made a few changes!

Code:

def elements(n)
        return [0] if n == 0
        return [0] if n == 1
        return [0, 1, 1] if n == 2
        lista = elements(n - 1) 
        lista << lista[-2] + lista[-1]
    end
    
16.10.2018 / 04:29