空心正方形内部正方形图案

问题描述 投票:0回答:1

这是我的程序正在做的:它以n作为输入并使用2^{n+1}-1计算Square边的长度,然后以每个正方形的顶点位于中间的模式打印'n'个正方形前一个正方形的一侧。以下是一些示例输出:

输入:2

输出:

#######
#..#..#
#.#.#.#
##...##
#.#.#.#
#..#..#
#######

输入:3

输出:

###############
#......#......#
#.....#.#.....#
#....#...#....#
#...#######...#
#..##.....##..#
#.#.#.....#.#.#
##..#.....#..##
#.#.#.....#.#.#
#..##.....##..#
#...#######...#
#....#...#....#
#.....#.#.....#
#......#......#
###############

我已经尝试解决这个问题了一段时间,问题是我无法使代码像任何给定数字的算法一样工作,这是我的代码,仅适用于n= 1 or 2

lenght = int(input('Please input an integer : '))
n=2**(lenght+1)-1
mid=int((n-1)/2)-1


print('#'*n)

i=-1
cnt1 = 0
midflag=1

while cnt1 < (n-2):
    print('#',end='')

    a='.'*(mid)+'#'
    if  lenght==1:
        a='.' 
    print (a,end='')
    print ('.'*(i),end='')

    if i==-1:
        print (a[::-1][1:],end='')
    else:
        print (a[::-1],end='')

    if midflag*mid>0:
        mid-=1
        i+=2
    else:
        mid+=1
        i-=2
        midflag=0

    cnt1 += 1

    print('#')

print('#'*n,end='')

关于如何使它适用于任何给定数字的任何建议?

python python-3.x algorithm
1个回答
0
投票

当然可以使它那样工作,但是我发现首先在内存中创建网格,然后在该网格中“绘制”形状更加容易。这样,您不必逐行生成最终输出,而不必同时考虑所有形状。

因此,我建议创建一个最初仅具有点且不具有散列的矩阵。然后迭代您必须绘制的不同形状(正方形或菱形),并将相应的哈希值放在该矩阵的正确坐标处。

请注意,输出在水平和垂直方向上都是对称的,因此您可以只关注矩阵的一个象限,而仅在最后通过沿X和Y轴镜像一个象限来生成另一个象限。] >

所以这是采用这种方法的代码:

length = int(input('Please input an integer:'))
# let n be the half of the total width, including the centre file
n = 2**length 

# create an empty grid, just for the bottom-right quadrant
grid = [['.']*n for _ in range(n)]

# Draw each of the partial shapes in that quadrant
for shape in range(length):
    if shape % 2: # draw one side of a diamond
        for i in range(1, n):
            grid[i-1][n-1-i] = '#'
        n //= 2 # adjust the size for the next square (if any)
    else: # draw 2 half-sides of a square
        for i in range(n):
            grid[n-1][i] = '#' # horizontal side
        for line in grid[:n]:
            line[n-1] = '#'    # vertical side

# Create the other 3 quadrants by mirroring, and join to a string 
print("\n".join(["".join(line[:0:-1] + line) for line in grid[:0:-1] + grid]))
© www.soinside.com 2019 - 2024. All rights reserved.