i want the print the below pattern using recursion and do not have to use any loops(strictly).
* * * * * * * * * * * * * *
* * * * * * * * * * * *
* * * * * * * * * *
* * * * * * * *
* * * * * *
* * * *
* *
* * * *
* * * * * *
* * * * * * * *
* * * * * * * * * *
* * * * * * * * * * * *
* * * * * * * * * * * * * *
i have did it without using recursion
n = 7
for i in range(n,0,-1):
for j in range(i,0,-1):
print("*",end=" ")
for j in range(2*(n-i)):
print(" ",end=" ")
for j in range(i,0,-1):
print("*",end=" ")
print()
for i in range(1,n):
for j in range(i 1):
print("*",end=" ")
for j in range(2*(n-i-1)):
print(" ",end=" ")
for j in range(i 1):
print("*",end=" ")
print()
can anyone help in printing the same patter using recursion and without using any loops(strictly)
i have tried using recursion but unable to print it properly and unable to visualize the code any further code using recursion:
def print_pattern(n, row=0):
if row == n:
return
print("* "*(n - row) " "*(2*row) "* "*(n - row))
print_pattern(n, row 1)
if row != 0:
print("* "*(n - row) " "*(2*row) "* "*(n - row))
n = 5
print_pattern(n)
CodePudding user response:
If the pattern always stays the same you could save it in a variable using var ='''pattern'''
In this case it would look like this:
pattern = '''* * * * * * * * * * * * * *
* * * * * * * * * * * *
* * * * * * * * * *
* * * * * * * *
* * * * * *
* * * *
* *
* * * *
* * * * * *
* * * * * * * *
* * * * * * * * * *
* * * * * * * * * * * *
* * * * * * * * * * * * * *'''
print(pattern)
CodePudding user response:
Use only row != -1 your code will work properly
def print_pattern(n, row=0):
if row == n:
return
print("* "*(n - row) " "*(2*row) "* "*(n - row))
print_pattern(n, row 1)
if row != -1:
print("* "*(n - row) " "*(2*row) "* "*(n - row))
n = 7
print_pattern(n)
CodePudding user response:
The check should be row != n - 1
:
def print_pattern(n, row=0):
if row == n:
return
print("* " * (n - row) " " * (2 * row) "* " * (n - row))
print_pattern(n, row 1)
if row != n - 1:
print("* " * (n - row) " " * (2 * row) "* " * (n - row))
n = int(input('Number of lines:'))
print_pattern(n)