Home > Software engineering >  Trying to draw a 'box' using python recursion
Trying to draw a 'box' using python recursion

Time:11-07

I am trying to use python recursion in order to draw a box, but have a hard time finding where to start. In principle I want to pass two numbers as arguments which will be the amount of '*''s that are printed both vertically and horizontally like this:

>>> drawRectangle(4, 4) 
****
*  *
*  *
****

CodePudding user response:

Whenever you are requesting a help from community you need to tell what you have tried so far, this way other members don't have to start from scratch.

def box(n, c, k): # n=number of rows, c=number of cols, k=number of rows to keep the track of original number
  if n>0 and c>0:
    if n==1:
      print("*"*c)
    elif n==k:
      print("*"*c)
    else:
      print("*" " "*(c-2) "*")
    box(n-1,c, k)

def create_box(n,c):
  box(n,c,n)

create_box(5, 7)

# output
*******
*     *
*     *
*     *
*******

CodePudding user response:

note: in python function names are snake case and not camel case (somthing_somthing and not SomthingSomthing).

for python conventions see PEP 8


this function will receive width and height as parameters and has another parameter first with default value True.

if height == 1 it will print a row of * and stop

if first == True it will print a row of * and will call it self again but with first = False and height - 1

else it will print one * and " " * (width - 2) and one * and will call itself again with height - 1

the first parameter allows us to print the first row as a full row and the rest up until height == 1 not as full rows

def draw_rectangle(width: int, height: int, first=True):
    if height == 1:
        print("*" * width)
    elif first:
        print("*" * width)
        draw_rectangle(width, height - 1, first=False)
    else:
        print("*"   " " * (width - 2)   "*")
        draw_rectangle(width, height - 1, first=False)


draw_rectangle(4, 4)

# output:
# ****
# *  *
# *  *
# ****
  • Related