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

如何在排列(permutations)列表中查找井字棋获胜组合键?

井字棋获胜校验逻辑问题修复

存在的问题

  • 第一个遍历排列的循环中,直接覆盖了player_moves变量,循环结束后该变量仅会保留最后一个排列结果,此前生成的所有排列都会丢失
  • 后续校验的嵌套循环逻辑错误:对单个三元组排列做遍历,得到的moves是1、2、3这类单个数字,和三元组类型的获胜组合key做相等判断,永远不会匹配成功
  • 获胜组合列表winning_combination重复定义了(3,6,9),同时遗漏了右下到左上的斜线获胜组合(3,5,7)

修复方案

按原有排列校验逻辑修改

from itertools import permutations

player_moves = [1, 3, 2]
# 存储所有排列结果,不覆盖原落子变量
player_perms = list(permutations(player_moves, 3))
computer_moves = []
# 修正获胜组合列表
winning_combination = [(1, 2, 3), (4, 5, 6), (7, 8, 9), (1, 4, 7), (2, 5, 8), (3, 6, 9), (1, 5, 9), (3, 5, 7)]

is_win = False
for key in winning_combination:
    if key in player_perms:
        print(f"{key} was found")
        is_win = True
        break
if not is_win:
    print("未匹配到获胜组合")

更高效的优化方案(无需生成排列)

使用集合子集判断,性能远高于生成全排列再匹配:

player_moves = {1, 3, 2} # 将落子转为集合
# 获胜组合也转为集合列表
winning_combination = [{1,2,3}, {4,5,6}, {7,8,9}, {1,4,7}, {2,5,8}, {3,6,9}, {1,5,9}, {3,5,7}]

for key in winning_combination:
    if key.issubset(player_moves):
        print(f"玩家获胜,匹配获胜组合:{key}")
        break

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 21:15:06