#πŸ”’ very simple recursion

16 messages Β· Page 1 of 1 (latest)

knotty aspen
#
'''
Write a recursive function power(x, n), where n is 0 or a postive integer. For example,
power(2, 10) will return 1024. Write a suitable base case, and for the general case use the
idea that xn = x * xn-1 .
'''
def power(x,n):
    if n < 0:
        return 1
    else:
        return x * power(x, n-1)
    
print(power(2,10))

someone please help me fix my code, without telling me the answer

fleet jacinthBOT
#

@knotty aspen

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

onyx linden
#

What's the problem?

knotty aspen
#

I get 2048 as the output

timid magnet
#

where n is 0 or a postive integer
yet your condition is n < 0

#

which is only satisfied when n is, well, less than 0, ie it is negative.

#

if n is an integer and is reduced by 1 each time the function recurses, it will stop when n = -1, not n = 0. because 0 is not < 0.

#

so essentially you are always recursing one extra time

knotty aspen
#

oh ok

#

got it

#

if n == 0: would be better

timid magnet
#

yes

fleet jacinthBOT
#
Python help channel closed

This help channel has been closed and it's no longer possible to send messages here. If your question wasn't answered, feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.

#

πŸ”’ very simple recursion