【发布时间】:2021-03-29 14:20:32
【问题描述】:
有人可以帮我将 for 循环 替换为 while 循环吗?
这个问题特别要求我们不要使用 for 循环。这就是为什么我需要将其替换为 while 循环
我在下面列出:
- 我的代码
- 输入和输出的示例测试
- 我们必须遵守的条件:
def matrix_equal(matrix1, matrix2):
"""
-------------------------------------------------------
Compares two matrices to see if they are equal - i.e. have the
same contents in the same locations.
Use: equal = matrix_equal(matrix1, matrix2)
-------------------------------------------------------
Parameters:
matrix1 - the first matrix (2D list of ?)
matrix2 - the second matrix (2D list of ?)
Returns:
equal - True if matrix1 and matrix2 are equal,
False otherwise (boolean)
------------------------------------------------------
"""
equal = True
if((len(matrix1) != len(matrix2)) or (len(matrix1[0]) != len(matrix2[0]))):
equal = False
for x in range(len(matrix1)):
if(equal == False):
break
for y in range(len(matrix1[0])):
num1 = matrix1[x][y]
num2 = matrix2[x][y]
if(num1 != num2):
equal = False
break
return equal
样本测试:
First matrix:
0 1 2
0 c a t
1 d o g
2 b i g
Second matrix:
0 1 2
0 c a t
1 d o g
2 b i g
Equal matrices: True
我们必须遵守的条件:
1. should not call input in the function
2. should not call print in the function
3. should not have multiple returns
【问题讨论】:
-
这看起来像作业,所以我不想发布更完整的解决方案。但这是一般的想法。
for负责创建预定义的迭代器并迭代其中的项目。while是“哑巴”,它只检查逻辑条件,并且会一直循环直到条件失败。它不会创建项目的迭代器,也不会自动前进到下一个项目。您必须手动完成所有这些操作,包括确保您使用的条件最终将评估为False,否则您将获得无限循环。