我的程序就是这样做的:它以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='')
关于如何使它适用于任何给定的数字有什么建议吗?你知道吗
当然可以这样做,但我发现先在内存中创建网格,然后在网格中“绘制”形状更容易。这样您就不必一行一行地生成最终的输出,而必须同时考虑所有的形状。你知道吗
所以我建议创建一个矩阵,最初只有点,没有散列。然后迭代要绘制的不同形状(正方形或菱形),并在矩阵的正确坐标处放置相应的散列。你知道吗
请注意,输出在水平和垂直方向上都是对称的,因此您可以只关注矩阵的一个象限,并仅在最后生成其他象限,只需沿X和Y轴镜像该象限即可。你知道吗
下面是采用这种方法的代码:
相关问题 更多 >
编程相关推荐