Search code examples
pythonnested-loops

Pattern in Python


I want to draw a diamond pattern (using 1's) in the zeros matrix 80x80. The first half is going really well but I get nothing but 0s in the second half.

img = np.zeros((80,80))

def draw_pic(image):
    for i in range(len(image)):
        for j in range(len(image[i])):
            print(int(image[i][j]), end = '')
        print()

def gen_diamond(image):
    ret = np.copy(image)
    for i in range(len(image)):
        for j in range(len(image[i])):
            if (i < len(image)/2 and j >= len(image[i])/2 - (i + 1) and j <= len(image[i])/2 + i):
                ret[i][j] = 1
            if (i > len(image)/2 and j >= len(image[i])/2 - (i + 1)and j <= len(image[i])/2 - i):
                ret[i][j] = 1


    return ret

draw_pic(gen_diamond(img))

Solution

  • Your error is in the range checks in the lower half. Let's look at the arithmetic for row 42 ...

            if (i > len(image)/2 and
                j >= len(image[i])/2 - (i + 1) and
                j <= len(image[i])/2 - i):
    

    Substituting the proper values, we have:

            if (42 > 40 and
                j >= 40 - (42 + 1) and
                j <= 40 - 42):
    

    That last condition cannot happen: you need to subtract the row number from the midpoint and take the absolute value. Simpler yet, just set your loop values directly to the ranges you need:

    row_mid = len(image) // 2
    col_mid = len(image[0]) // 2
    
    for row in range(row_mid):
        for col in range(col_mid-row, col_mid+row):
            print(row, col)
            ret[row, col] = 1
    
    for tmp in range(row_mid):
        row = len(image) - tmp    # Work from the bottom up
        for col in range(col_mid-tmp, col_mid+tmp):
            ret[row, col] = 1 
    

    Output for a 10x10 array:

    0000000000
    0000110000
    0001111000
    0011111100
    0111111110
    0000000000
    0111111110
    0011111100
    0001111000
    0000110000
    

    I'll trust you to adjust the boundary conditions. :-)