Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I make a square with a specified circumference and add margin?

I am trying to make a square path of a specified length:

I made a function – and if I put 20 then I get a 6×6 matrix.

How can I add a margin of 0’s of eg. 3 fields thickness?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

like this

0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 1 1 1 1 1 1 0 0 0
0 0 0 1 1 1 1 1 1 0 0 0
0 0 0 1 1 1 1 1 1 0 0 0
0 0 0 1 1 1 1 1 1 0 0 0
0 0 0 1 1 1 1 1 1 0 0 0
0 0 0 1 1 1 1 1 1 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0
def square(length): return [
    [1 for _ in range(length//4+1)]
    for _ in range(length//4+1)
]

for x in square(24):
    print(x)

>Solution :

Here’s one way. One caution here is that, because of the way I duplicated the zero rows, those are all the same list. If you modify one of the zero rows, it will modify all of them.

def square(length): 
    zeros = [0]*(length//4+7)
    sq = [zeros] * 3
    sq.extend( [
        ([0,0,0] + [1 for _ in range(length//4+1)] + [0,0,0] )
        for _ in range(length//4+1)
    ])
    sq.extend( [zeros]*3 )
    return sq

for x in square(24):
    print(x)

Here’s a numpy method.

import numpy as np
def square(length): 
    c = length//4+1
    sq = np.zeros((c+6,c+6)).astype(int)
    sq[3:c+3,3:c+3] = np.ones((c,c))
    return sq

print( square(24) )
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading