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

反向八皇后问题(判断皇后互吃)Python代码报错排查

八皇后互吃校验报错修复

问题背景

给定国际象棋棋盘上8个皇后的位置,若至少存在一对皇后可互相攻击(互吃)则输出YES,否则输出NO。
现有实现代码执行皇后对角线互吃逻辑校验时,Python抛出如下报错:

unsupported operand type(s) for Sub: "str" and "str"

原有错误代码如下:

a, b = input().split()
c, d = input().split()
e, f = input().split()
g, h = input().split()
i, j = input().split()
k, l = input().split()
m, n = input().split()
o, p = input().split()
#check cross or straight
if a==c or c==e or e==g or g==i or i==k or k==m or m==o or o==a or b==d or d==f or f==h or h==j or j==l or l==n or n==p or p==b:
    print("YES")
#check diagonally
elif a==b and c==d or c==d and e==f or e==f and g==h or g==h and i==j or i==j and k==l or k==l and a==b:
    print("YES")
elif abs(int(a-b))==abs(int(c-d)) or abs(int(c-d))==abs(int(e-f)) or abs(int(e-f))==abs(int(g-h)) or abs(int(g-h))==abs(int(i-j)) or abs(int(i-j)) == abs(int(k-l)) or abs(int(k-l))==abs(int(a-b)):
    print("YES")
else:
    print("NO")

输入规则:逐行输入8组皇后棋盘坐标,每组内两个坐标值用空格分隔,输入样例如下:

1 3
4 8
6 1
5 5
2 7
8 6
7 4
3 2

报错原因

  • 核心触发原因:input().split()读取到的坐标值是字符串类型,代码中写a-b时未提前将a、b转为整型,字符串类型不支持减法运算,直接触发类型错误。
  • 原有代码逻辑本身存在缺陷:一是仅校验了部分相邻皇后的位置关系,未覆盖8个皇后的所有两两组合,存在大量漏判场景;二是对角线判断逻辑错误,a==b仅能判断坐标在x=y这一条对角线上的特殊情况,无法覆盖所有对角线场景。

修复方案

  1. 读取输入时直接将坐标值转为整型,从根源避免类型运算错误
  2. 将所有皇后坐标存入列表,遍历所有两两组合做校验,覆盖所有可能的互吃场景
  3. 严格遵循皇后互吃判断规则:两个皇后横坐标相同(同行)、纵坐标相同(同列)、横纵坐标差的绝对值相等(同对角线),满足任意一条即判定为可互吃

修复后可正常运行的代码:

# 读取8个皇后的坐标,统一转整型存储
queens = []
for _ in range(8):
    x, y = map(int, input().split())
    queens.append((x, y))

has_attack = False
# 遍历所有皇后两两组合校验
for i in range(8):
    x1, y1 = queens[i]
    for j in range(i+1, 8):
        x2, y2 = queens[j]
        # 同行、同列、同对角线三种互吃场景判断
        if x1 == x2 or y1 == y2 or abs(x1 - x2) == abs(y1 - y2):
            has_attack = True
            break
    if has_attack:
        break

print("YES" if has_attack else "NO")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 23:39:20