In Python, i want to print concentric square for that i have written a code but i am not getting desired output

前端 未结 4 2030
伪装坚强ぢ
伪装坚强ぢ 2021-01-16 20:01

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 answ         


        
相关标签:
4条回答
  • 2021-01-16 20:13

    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()
    
    0 讨论(0)
  • 2021-01-16 20:20

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

    n = int(input())
    
    answer = []
    k = 0
    for i in range(n):
        temp = [(n-k) for _ in range(2*n - 1)]
        side = [x for x in range(n, n-k, -1)]
        answer.append(side + temp[k:len(temp) - k] + side[::-1])
        k += 1
    
    k = 2
    for i in range(n-1):
        answer.append(answer[n-k])
        k += 1
    
    for a in answer:
        print(''.join(map(str, a)), end='\n\n')
    
    0 讨论(0)
  • 2021-01-16 20:21

    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])
    
    0 讨论(0)
  • 2021-01-16 20:21

    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.

    0 讨论(0)
提交回复
热议问题