beginner_coder
beginner_coder

Reputation: 61

adding parenthesis in recursive function

I'm simply looking to add a parenthesis at the end of my recursive function.. I'm literally just missing the final parenthesis, but I can't figure out how to add it in! Any help is greatly appreciated!

My code:

def sum( n ): 

    if n == 0:
        return '1'

    elif n == 1:
        return '(1+1)'

    elif n == 2:
        return '((1+1)+(1+1))'

    elif n == 3:
        return '(((1+1)+(1+1))+((1+1)+(1+1)))'

    else:
        return '((((1+1)+(1+1))+((1+1)+(1+1)))' + ')'sum_power2(  n - 1  )

Upvotes: 0

Views: 186

Answers (2)

McGrady
McGrady

Reputation: 11477

Try this:

def sum_power(n,tmp=''):
    tmp = '1' if not tmp else '(' + tmp + '+' + tmp + ')'
    if n == 0:
        return tmp
    else:
        n -= 1
        return sum_power(n,tmp)


print(sum_power(2))

Upvotes: 0

Miriam Farber
Miriam Farber

Reputation: 19634

Just switch the order in the last row, so it would be

def sum_power2( n ): 

    if n == 0:
        return '1'

    elif n == 1:
        return '(1+1)'

    elif n == 2:
        return '((1+1)+(1+1))'

    elif n == 3:
        return '(((1+1)+(1+1))+((1+1)+(1+1)))'

    else:
        return '((((1+1)+(1+1))+((1+1)+(1+1)))' + sum_power2(  n - 1  )+')'

Upvotes: 1

Related Questions