我是 python 和编程的新手,并且得到了这个练习。我可以使用下面的代码获得预期的结果,但想知道使用 Python 3.x 还有什么其他方法可以解决这个问题。
练习是取一个数字并生成以下模式:
用户输入:1
X
用户输入:2
O O O
O X O
O O O
用户输入:3
X X X X X
X O O O X
X O X O X
X O O O X
X X X X X
等等...
这是我所拥有的:
def makePattern():
num = int(input("Enter a number: "))
def makeBoxes(num):
width = (num * 2) - 1
midpoint = num - 1
matrix = [ [ "X" for i in range(width) ] for j in range(width) ]
for d1 in range(width):
mpD1 = abs(midpoint - d1)
for d2 in range(width):
mpD2 = abs(midpoint - d2)
if (mpD1 % 2 == 1):
if mpD2 <= mpD1:
matrix[d1][d2] = "O"
if (mpD2 % 2 == 1):
if mpD1 <= mpD2:
matrix[d1][d2] = "O"
printBoxes(matrix,width)
makePattern()
def printBoxes(matrix,width):
holder = ""
count = 1
for row in matrix:
for point in row:
holder += (point + " ")
if count % width == 0:
print(holder)
holder = ""
count += 1
makeBoxes(num)
makePattern()