You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何编写Python条件判断语句验证5x5矩阵符合宾果规则

5x5宾果矩阵合法性验证代码实现

嘿,我来帮你搞定这个宾果矩阵的验证逻辑!咱们先明确核心规则:

  • 第1列(索引0)的整数必须在 1-15 范围内
  • 第2列(索引1)的整数必须在 16-30 范围内
  • 第3列(索引2)的整数必须在 31-45 范围内
  • 第4列(索引3)的整数必须在 46-60 范围内
  • 第5列(索引4)的整数必须在 61-75 范围内

下面是补全if判断逻辑后的完整代码,我还加了测试示例帮你直观验证:

# Rules are simple
table = [
    [12, 17, 34, 48, 70],   # first column integers are allowed 1-15
    [14, 25, 40, 56, 61],   # second column integers are allowed 16-30
    [6, 30, 43, 46, 72],    # third column integers are allowed 31-45
    [12, 16, 42, 63, 65],   # fourth column integers are allowed 46-60
    [4, 31, 34, 49, 67]     # fifth column integers are allowed 61-75
]

def is_right_matrix(table):
    for i in range(len(table)):
        for j in range(len(table[i])):
            num = table[i][j]
            # 根据列索引匹配对应数值范围,不符合则直接返回False
            if (j == 0 and not (1 <= num <= 15)) or \
               (j == 1 and not (16 <= num <= 30)) or \
               (j == 2 and not (31 <= num <= 45)) or \
               (j == 3 and not (46 <= num <= 60)) or \
               (j == 4 and not (61 <= num <= 75)):
                return False
    # 所有元素都符合规则,返回True
    return True

# 测试给定的矩阵(会输出False,因为第四行第四列的63超出了46-60的范围)
print(is_right_matrix(table))

代码逻辑拆解:

  1. 双层循环遍历矩阵的每一个元素:外层循环处理行,内层循环处理列
  2. 针对每个元素,通过列索引j匹配对应的数值区间检查
  3. 一旦发现任意元素不符合规则,立刻返回False并终止检查(避免无效遍历)
  4. 若所有元素都通过验证,最终返回True

内容的提问来源于stack exchange,提问作者Kerli Uib

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 04:28:13