我试图使用python递归来绘制一个框,但很难找到从哪里开始。原则上,我想传递两个数字作为参数,它们将是垂直和水平打印的"*"的数量,如下所示:
>>> drawRectangle(4, 4)
****
* *
* *
****
每当你向社区请求帮助时,你需要告诉你到目前为止你做了什么,这样其他成员就不必从头开始了。
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
*******
* *
* *
* *
*******
注:python
中function names
是snake case
而不是camel case
(somthing_somthing而不是SomthingSomthing)
python约定见PEP 8
此函数将接收width
和height
作为参数,并有另一个参数first
,默认值为True
。
如果是height == 1
,它将打印一行*
并停止
如果是first == True
,它将打印一行*
,并再次调用self,但是包含first = False
和height - 1
否则,它将打印一个*
和一个" " * (width - 2)
和一个*
,并再次使用height - 1
调用自己
first
参数允许我们将第一行打印为完整行,直到height == 1
的其余行不打印为完整行
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:
# ****
# * *
# * *
# ****