Skip to content Skip to sidebar Skip to footer

In Python, I Want To Print Concentric Square For That I Have Written A Code But I Am Not Getting Desired Output

input n taken here n=int(input()) answer=[[1]] for i in range(2, n+1): t=[i]*((2*i)-3) answer.insert(0, t) answer.append(t) for a in answer: a.insert(0,i)

Solution 1:

Here is the solution to your problem with the right algorithm and output:

n = int(input())

answer = []
k = 0for i inrange(n):
    temp = [(n-k) for _ inrange(2*n - 1)]
    side = [x for x inrange(n, n-k, -1)]
    answer.append(side + temp[k:len(temp) - k] + side[::-1])
    k += 1

k = 2for i inrange(n-1):
    answer.append(answer[n-k])
    k += 1for a in answer:
    print(''.join(map(str, a)), end='\n\n')

Solution 2:

Your logic doesn't seem to be right, and there is some bad indentation in your code as well.

To print the output properly instead of a list you can do:

for a in answerfinal:
    for i in a:
        print(i, end='')
    print()

Solution 3:

You can replace the commas and spaces with nothing and then exclude the brackets:

for a in answerfinal:
    print(a.replace(', ', '')[1:-1])

Full code below:

n=int(input())

answer=[[1]]for i in range(2, n+1):
    t=[i]*((2*i)-3)
    answer.insert(0, t)
    answer.append(t)
    for a in answer:
        a.insert(0,i)
        a.append(i)
answerfinal=[]

for a in answer:
    answerfinal.append("".join(str(a)))

for a in answerfinal:
    print(a.replace(', ', '')[1:-1])

Solution 4:

Using

for i in range(2*n-1):
    print()
    for j in range(len(answerfinal[i])):
        print(answerfinal[i][j], end='')

instead of

for a in answerfinal:
    print(a)

might help.

Post a Comment for "In Python, I Want To Print Concentric Square For That I Have Written A Code But I Am Not Getting Desired Output"