Recursive function of natural numbers is showing negative

Asked

Viewed 130 times

1

I need a recursive function (exercise) that prints all natural numbers between A and B:

def cont(a, b):
if a < b:
    print(a)
    cont(a + 1, b)


cont(-3, 12)

The problem is that the way I did, the negative numbers are being printed as well.

  • Did the answer solve your question? Do you think you can accept it? See [tour] if you don’t know how you do it. This would help a lot to indicate that the solution was useful for you. You can also vote on any question or answer you find useful on the entire site (when you have 15 points).

1 answer

3

You have two different conditions, one is the condition of what must be printed, and must be all numbers greater than or equal to zero, the other condition is up to when must continue recursion.

def cont(a, b):
    if a >= 0:
        print(a)
    if a < b:
        cont(a + 1, b)

cont(-3, 12)

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

It has how to do an intermediate function to avoid recursion on unnecessary items, ie already starting from scratch. Just as I would iteratively, what alias is the best way to do this kind of algorithm. I don’t like these exercises that force the use of recursion.

And there is no validation if the first argument is less than the second, which should even be done in this intermediate function that I said.

Browser other questions tagged

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