0

I want to write a function in Python which takes an integer, then returns the number of combinations the given integer can be added to with the numbers 3, 2, and 1.

For example, if I call the function with the number 2, I would get the response of 2, since there are two combinations of 3, 2 and 1 to get to 2: 1,1 and 2.

Any advice on how to go about this?

Here's what I have coded:

def countStairs(n):
    if n == 0:
    print(number)
    elif n == 2:
        return countStairs(n-1)
        return countStairs(n-2)
        number = number + 1
    elif n == 1:
        return countStairs(n-1)
        number = number + 1
    else:
        return countStairs(n-3)
        number = number + 1
Steffi Keran Rani J
  • 3,667
  • 4
  • 34
  • 56
  • 2
    Explanation: you should write a recursive function that goes down recursively from `n` to zero and checks all combinations of `n` which are made from the combinations of `n-1`, `n-2` and `n-3`. Think what should be the stop condition and start implementing. – Nir Alfasi Nov 17 '17 at 04:24
  • @alfasin Thanks! I've updated with a draft of my code with what I think you mean. I have a base case (stop condition) and then recursively subtract 1, 2, and 3 while counting it if it works. Thoughts? –  Nov 17 '17 at 04:37
  • To properly format code, select it in the editor and press the `{}` button in the editor. – Chai T. Rex Nov 17 '17 at 04:39
  • No code executes after a `return`, so having a line on the same indentation after a `return` is a dead giveaway your logic doesn't work. Also, for any given `n` over the terminal condition, you should count all stairs from `n-1` down, from `n-2` down and from `n-3` down, all of them, and add them together. – Amadan Nov 17 '17 at 04:47
  • Since you're counting the number of options if `n == 0` it means that you've reached one of the options - return 1 (now you're not returning anything). What should you return if `n < 0` ? what is the recursion step ? – Nir Alfasi Nov 17 '17 at 05:07
  • Your question is similar to [this one](https://stackoverflow.com/questions/1106929/how-to-find-all-combinations-of-coins-when-given-some-dollar-value) about combinations of coins that add to some dollar value, and in general is known as integer partitioning, I think. – eugenhu Nov 17 '17 at 07:01

0 Answers0