0

I want to make sure 'rep' isn't made 0 at the beginning of each recursion. At the current point it is defaulted to starting at 0, but I want it to save the value of rep+=1.

Is there an easy fix?

def printPattern(n,k,rep =0):
    'prints a pattern of stars'
    if n == k:
        print ('{}{}'.format(' '*rep,'*'*n))
    elif n%2 == 0:
        rep+=1
        print ('{}{}'.format(' '*rep,'*'*n))
        printPattern(n+1,k)
    else:
        rep+=1
        print ('{}*'.format(' '*rep))
        printPattern(n+1,k)
1
  • 3
    Pass your rep to recursive function call..
    – Rohit Jain
    Commented Oct 16, 2012 at 16:32

2 Answers 2

1

You can start by actually passing rep in your recursive call

printPattern(n+1,k, rep)

def printPattern(n,k,rep =0):
    'prints a pattern of stars'
    if n == k:
        print ('{}{}'.format(' '*rep,'*'*n))
    elif n%2 == 0:
        rep+=1
        print ('{}{}'.format(' '*rep,'*'*n))
        printPattern(n+1,k, rep)
    else:
        rep+=1
        print ('{}*'.format(' '*rep))
        printPattern(n+1,k, rep)
1
    rep+=1
    print ('{}{}'.format(' '*rep,'*'*n))
    printPattern(n+1,k, rep)

If you pass new value of rep as 3rd parameter, then default value 0 will not be used.

So, when you call this function the first time, you can actually skip using the 3rd parameter, then the default value will be used. But the next time, every recursive call to this function will take rep as 3rd parameter, passed as the current value of rep

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.