Home > other >  problem with a recursive function code for beginners
problem with a recursive function code for beginners

Time:01-03

I'm currently learning about recursive functions on Python. So far I've solved this task:

A gold coin is placed in the safe and the safe is closed. The safe is then placed in another, larger safe and another gold coin is added. The second safe is placed in a third, even bigger safe, adding two more gold coins, etc. So with the first safe, 1 gold coin is placed in the next, with the second 2 gold coins, with the third 3 gold coins, etc.

Create a recursive function that takes the sequence number of the safe as an argument and returns the total number of gold coins hidden in this safe. `

def gold(n):
    if n == 1:
        return 1
    else:
        return gold(n-1) (n-1)

`

Now, I need to write a code where the number of coins increases like this: a gold coin is placed in a safe and another coin is added, then the safe is placed into another safe and a coin is added. Then the safe is placed into the fourth safe and two coins are added. The code should return these values:

>>> gold(7)
10
>>> gold(8)
11

So far I've only got this:

def gold(n):
    if n == 1:
        return 2
    else:

How can I do so that usually the number of gold coins is increased by one coin but every 4th, 7th, 10th, ...etc it increases by two? I know this is probably a very easy and stupid question, but I can't figure it out

CodePudding user response:

You probabbly wants something like this:

Edited:

def gold(n):
    if n == 1:
        return 1
    elif n == 2:
        return 2
    elif n % 2 == 0:
        return gold(n-1)   1
    else:
        return gold(n-1)   2

CodePudding user response:

Maybe this is what you want

def gold(n):
    if n == 1:
        return 1
    if (n - 1) % 3 == 0:
        return 2   gold(n-1)
    else:
        return 1   gold(n-1)
  • Related