2

I'm supposed to be writing a function that find the amount of shoes a given number of dogs would need. It can easily be done with multiplication, but we're required to use recursion, so i have

def dogShoes(n):
    total = 0
    if n>0:
        shoes =   n + dogShoes(n)
        total = total + 1
        if total == 4:
            return shoes

But I now realize that line 4 will go towards infinity and the bottom part that I though would stop it won't even be implemented. Is there a way to say when total is 4, stop and return the answer without shoes going towards infinity?

Eli Sadoff
  • 7,173
  • 6
  • 33
  • 61
Malaikatu Kargbo
  • 313
  • 2
  • 12

3 Answers3

5

You can simplify your function a lot:

def dogShoes(n):
    if n == 0:
        return 0
    else:
        return 4 + dogShoes(n-1)

Since you have to use recursion instead of just returning n * 4 you can simply rewrite multiplication as addition (recursively).

What a weird task...

Keiwan
  • 8,031
  • 5
  • 36
  • 49
2

You're calling your function recursively, but never changing the parameter, thus giving infinite recursion. Try:

>>> def dog_shoes(n):
...   if n > 0:
...     return 4 + dog_shoes(n-1)
...   else:
...     return 0
...
>>> dog_shoes(1)
4
>>> dog_shoes(2)
8
>>> dog_shoes(3)
12
Will
  • 4,299
  • 5
  • 32
  • 50
0
def Mul(n, x):
    if n==1:
        return x
    else:
        return x+ Mul(n-1,x)

Here's a simple multiplication function using Python recursion using two arguments.

Mul(3,3)
>>>9
Yevhen Kuzmovych
  • 10,940
  • 7
  • 28
  • 48