halo32008 halo32008 - 7 months ago 17
Python Question

Re-writing function recursively

I am trying to print out a hollow square, recursively. I cannot figure out how to re-write the function

def hollowSquare()
to have a recursive call.

Note: I have to have 3 parameters in the hollowSquare function for this assignment, count is used to keep track in where I'm drawing at.

def validateInput():
n =True
while n != False:
height = int(input("Please enter the height of you square (must be > 0): "))
if height < 0:
validateInput()
else:
symb = input("Please enter a character for your square:")

return(height,symb)


def hollowSquare(height,symb,count):
innerSquare = height -2
print ('*' * height)
for i in range(innerSquare):
print ('*' + ' ' * innerSquare + '*')
print ('*' * height)







def main():
height,symb = validateInput()
count =0
hollowSquare(height,symb,count)


main()

Answer

The count variable is not used in the looping version, so I'd say that's what's intended to be the "loop counter" for the recursive version. You could make it a default argument and start it at 0 so that it doesn't have to be called with an explicit 0, as shown below. Give the function a way to determine whether it should stop or keep recurring, show below with if count < height-1: .. else:. If it's not time to stop, it checks whether it's the first row, in which case it prints the starting row. Otherwise, it prints one of the middle rows. Then comes the recursive call, which will do the process again. When count < height-1 is no longer true, it will print the ending row and stop recurring. Note that I've replaced your hardcoded '*' with symb.

I've included calls to each function for testing.

def hollowSquare(height, symb, count=0):
    if count < height-1:
        if not count:
            print (symb * height)
        else:
            print (symb + ' ' * (height-2) + symb)
        hollowSquare(height, symb, count+1)
    else:
        print (symb * height)

hollowSquare(5, '*')

print('-----')

def hollowSquare(height,symb,count):
    innerSquare = height -2
    print ('*' * height)
    for i in range(innerSquare):
        print ('*' + ' ' * innerSquare + '*')
    print ('*' * height)

hollowSquare(5, '*', 0)
Comments