How to get the correct output in this homework problem?

This should do the trick:

for i in range(-number + 1, number):
    n = abs(i) + 2
    print("".join([
        str(j) for j in 
        list(range(number, n - 2, -1)) + # first part (54321)
        ([n - 1] * (n * 2 - 4)) + # middle part (1111)
        list(range(n, number + 1)) # end part (2345)
    ])) # "".join converts the list to a string

The

for i in range

is for the vertical axis, the statement,

“”.join(str(j) for j in list(…) + […] + list(…))

joins the lists together and converts it to string,

list(range(number, n – 2, -1))

is for the start beginning (here: 54321),

([n – 1] * (n * 2 – 4))

is for the middle part (here: 1111), and

list(range(n, number + 1))

is the ending (here: 2345)

Leave a Comment