创建一个矩阵 MxN,其中包含以元素数字表示的整数输入条件 (python) [closed]

Create a matrix MxN with integers inputs with a condition in the digits of the elements (python) [closed]

提问人:kcantor 提问时间:1/12/2021 最后编辑:kcantor 更新时间:1/12/2021 访问量:209

问:


想改进这个问题吗?更新问题,使其仅通过编辑这篇文章来关注一个问题。

2年前关闭。

我想创建一个矩阵 MxN。此矩阵从用户获取输入。我想使用防御性编程,使矩阵的元素没有数字 2。 例如,用户不应使用 12、20、21、22 等整数,...32,42,102,...作为矩阵的输入。 我的尝试如下,但我不知道如何使用数字 2 创建此条件。

M = int(input("Enter number of rows"))
N = int(input("Enter number of columns"))
count = 1
matrix = []
for i in range(M):
    list = []
    for j in range(N):
        list.append(count)
        count += 1
    matrix.append(list)

我创建了这个矩阵,但我不知道如何添加带有数字限制的条件作为输入。

Python 防御性编程

评论

0赞 Grizzle 1/12/2021
如果你能提供一个简单的例子来说明你到目前为止所做的事情,那将是有用的,有人可以帮助你指出正确的方向。

答:

1赞 Grizzle 1/12/2021 #1

我能想到的最简单的选择是将 row 和 col 的输入保留为字符串,并在继续之前检查它们是否包含 a。2

check = True
while check:
    row = input("Enter number of rows")
    col = input("Enter number of columns")

    if '2' not in row or '2' not in row:
        check = False
        row = int(row)
        col = int(col)
    else:
        print("input error, number 2 is now allowed")


count = 1
matrix = []
for i in range(row):
    list = []
    for j in range(col):
        list.append(count)
        count += 1
    matrix.append(list)