空心方形内方形图案

2024-09-27 07:17:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我的程序就是这样做的:它以n作为输入,用2^{n+1}-1计算正方形边长,然后按每个正方形的顶点放在前一个正方形边长中间的模式打印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='')

关于如何使它适用于任何给定的数字有什么建议吗?你知道吗


Tags: 代码程序inputif数字elseintend
1条回答
网友
1楼 · 发布于 2024-09-27 07:17:08

当然可以这样做,但我发现先在内存中创建网格,然后在网格中“绘制”形状更容易。这样您就不必一行一行地生成最终的输出,而必须同时考虑所有的形状。你知道吗

所以我建议创建一个矩阵,最初只有点,没有散列。然后迭代要绘制的不同形状(正方形或菱形),并在矩阵的正确坐标处放置相应的散列。你知道吗

请注意,输出在水平和垂直方向上都是对称的,因此您可以只关注矩阵的一个象限,并仅在最后生成其他象限,只需沿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]))

相关问题 更多 >

    热门问题