简体   繁体   中英

failed to print the pattern as expected for a given positive integer n in python

I wanted to print a particular pattern as shown below and for that, I created a list of lists with just [1] in it.

Then I ran a for loop from i= 2 to n and in each iteration, I have added [i]*(2i-3) in top of the list as well as in the bottom.

Then add i on both sides of all sub_lists.

Below is the code i have used:

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=[]

print(len(answer))

# we join the elements of the string without space
for a in answer:
  answerfinal.append(''.join(map(str, a)))
#print 
for a in answerfinal:
    print(a)

I was supposing to get an answer like this, if input given is 4:

4444444
4333334
4322234
4321234
4322234
4333334
4444444

But what I got is this:

444444444
44333333344
4433222223344
4321234
4433222223344
44333333344
444444444

Not sure where I was wrong.

This is one of the key Python blunders. The problem here is that you create the list t , then you add t to the beginning, then you add THE VERY SAME t to the end. It's not a copy, it is a reference to the same list. So, when you run through the list of lines, you're adding to the ends twice. Change

  answer.append(t)

to

  answer.append(t[:])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM