Return the Fibonnaci elements from the term passed to the first

Asked

Viewed 92 times

-1

I have made the return of some specific elements already, but I am trying to return up to the first. In the code below I returned a certain element, as I create from now until the first, until the fifth and until the decimo?

def element( f )
        return  f  if f <= 1
        element( f - 1 ) + element( f - 2 )
    end
  • Explain the need better. Be clearer in what the algorithm should do. I could understand what you did and that you want several numbers, but how do you want this to be provided? Not knowing where you want to go no way serves.

  • I need to return the elements of Fibonacci until the tenth, I will put an example of the error and you will have an idea ! Note: I already have a spec created. Fibonacci returns the fibonnacci elements up to the tenth Failure/Error: expect(Fibonacci.new.Elements(10)). to eq [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55] expected: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55] got: 10 (Compared using =) # . /spec/fibonacci_spec.Rb:29:in `block (2 levels) in <top (required)>' Finished in 0.04687 Seconds (files Took 1.27 Seconds to load) 7 examples, 3 failures

2 answers

1


The description wants to return a list and not the end term, so you must manipulate the returns with lists, something like that:

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)

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

  • I’ll try here ! Thank you

  • @Lucascordeiro See on [tour/ the best way to say thank you.

  • All right ! His method worked almost right, he just returns me saying expected: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55] got: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

  • I made a small change, removing the Return list, and in the Return [0, 1] I added another 1, getting Return [0 ,1 ,1], so it worked by returning up to the fifth element and up to the tenth element, less to the first

0

I did as Maniero said, I just made a few minor 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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.