【发布时间】:2022-01-19 22:12:26
【问题描述】:
我有以下代码,出于教学目的,我想从这里简化为使用迭代。我希望学生能够看到任何重复(例如模式)并使用 for 或 while 循环来实现这一点。
解决这个问题的最佳方法是什么?
https://trinket.io/python/5e56cf6a5c
def matrix():
print("---The Matrix---")
#create a 1d array of 7 stars
matrix1=[
["*","*","*","*","*","*","*"],
["*","*","*","*","*","*","*"],
["*","*","*","*","*","*","*"],
["*","*","*","*","*","*","*"],
["*","*","*","*","*","*","*"],
["*","*","*","*","*","*","*"],
["*","*","*","*","*","*","*"]
]
#user enters a number
number=int(input("Enter number:"))
#you are always finding the remainder on each row to place the X
remainder=number%7
#an 'X' is placed in the position of the number
#remainder-1 because we start at index 0
if number<1:
matrix1[0][0]="X"
elif number<=7:
matrix1[0][remainder-1]="X"
elif number>7 and number<15:
matrix1[1][remainder-1]="X"
elif number>14 and number<22:
matrix1[2][remainder-1]="X"
elif number>21 and number<29:
matrix1[3][remainder-1]="X"
elif number>28 and number<36:
matrix1[4][remainder-1]="X"
elif number>35 and number<43:
matrix1[5][remainder-1]="X"
elif number>42 and number<50:
matrix1[6][remainder-1]="X"
#the updated matrix is printed.
print(matrix1)
matrix()
根本不使用迭代,建议这样做:
def matrix():
print("---The Matrix---")
# create a 2d array of 7x7 stars
matrix1 = [["*" for _ in range(7)] for _ in range(7)]
number = int(input("Enter number: "))
matrix1[number // 7][number % 7] = "X"
# print the matrix
print('\n'.join(''.join(row) for row in matrix1))
matrix()
我无法理解以下内容:
比如说“14”。 matrix1[number // 7][number % 7] = "X" number//7 = 2 and number%7 = 0。这应该把X放在第2行和位置0?
【问题讨论】:
-
它确实将 14 放入
matrix1[2][0] -
关于您的跟进:该建议并不完全正确。你应该做
matrix1[(number-1)//7][(number-1)%7] = 'X'。对于“14”,您最终会修改第 1 行的位置 6。 -
就在附近 - 但不适用于 0 trinket.io/python/a19b22da26
-
@Compoot 也许我对所需的行为感到困惑。我想如果
number是n,那么我们要改变从左上角开始的第n个条目来改变。如果是这样,那我们为什么会期望收到输入“0”? -
@Compoot 饰品使用 Python 2。您使用的是 python 2 还是 python 3?
标签: python loops if-statement