0

My program read an integer number N, that correspond to the order of a Bidimentional array of integers, and build the Array according to the below example. I want to fill the middle elements like my expected output.

My code:

n = int(input())
for row in range(1, n+1):
    for colum in range(1, n+1):
        print(row, end="   ")
    print()


Input:

5 


My output:

1   1   1   1   1   
2   2   2   2   2
3   3   3   3   3   
4   4   4   4   4
5   5   5   5   5


The output I want:

1   1   1   1   1
1   2   2   2   1
1   2   3   2   1
1   2   2   2   1
1   1   1   1   1

I want to fill the middle elements like this. The height number at the middle then the second height number and so on..

3 Answers 3

1

for the "1-2-3-2-1" sequence, you can get it as the "minimum between row and n + 1 - row" - - min(row, n + 1 - row). (And the symmetrical for column) - and then you print the min of this calculation for row and cols:

n = int(input())
for row in range(1, n+1):
    for column in range(1, n+1):
        mrow = min(row, n + 1 - row)
        mcol = min(column, n + 1 - column) 
        print(min(mrow, mcol), end="   ")
    print()
Sign up to request clarification or add additional context in comments.

Comments

0

I hope this is not a homework question, but i will help you.
This can be done a lot more easily with lists!:

def cell_value(i, j, n_rows):
    return min(
        abs(i - -1),
        abs(i - n_rows),
        abs(j - -1),
        abs(j - n_rows),
    )

rows=int(input("Enter the number of rows:"))
row2 = [
    [
        cell_value(i, j, rows)
        for j in range(rows)
    ]
    for i in range(rows)
]

for r in row2:
    print(*r)

Or it can be done even more easily like this below:

numberOfRows = int(input("Enter the number of rows:"))
listOut = [[1]*numberOfRows] * numberOfRows #grid of 1s of appropriate size
for j in range(int((numberOfRows+1)/2)): #symmetrical, so only look to the middle
    if j > 0:
        listOut[j] = list(listOut[j-1]) #copy previous row
    for i in range(int((numberOfRows+1)/2)):   
        if i>=j:
            listOut[j][i] = j+1
            listOut[j][numberOfRows-(i+1)] = j+1
    #copy current row to appropriate distance from the end
    listOut[numberOfRows-(j+1)] = list(listOut[j])
for row in listOut:
    print(row)

Both of the above programs give the SAME result

Enter the number of rows:5
1 1 1 1 1
1 2 2 2 1
1 2 3 2 1
1 2 2 2 1
1 1 1 1 1

Note:this is only possible for odd numbers! Let me know if you have any doubts...
Cheers!

Comments

0

enter image description here

`for i in range(n):   
````print((n-i)*" ",end=" ")
````print((i+1)*"* ")

1 Comment

see the expected output, your answer doesn't address that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.