试用deepseek生成判断一套麻将牌是否胡牌的程序 - l1t1/note GitHub Wiki

第一次生成的代码运行出错,错误的原因是代码中尝试对字符串类型的牌进行数值操作(如 tile + 1),而 Unicode 麻将牌是字符串类型,不能直接进行数值操作。我们需要重新设计逻辑,确保正确处理字符串类型的牌。

第二次生成的自己的测试没有通过。它说:感谢反馈!我重新检查了代码,发现第二个示例 hand2 = "🀇🀇🀇🀈🀈🀈🀉🀉🀉🀙🀙🀙🀙🀙" 的预期结果应该是 不胡牌,但代码可能因为逻辑问题返回了错误的结果。

问题出在 将牌检查顺子检查 的逻辑上。我们需要确保:

  1. 将牌只能有一对。
  2. 剩余的牌必须严格组成 4 组顺子或刻子。

我告诉它,其实这个错误原因是有5张一筒。它理解了。 这是经过两次提示后生成的,还有个漏洞我自己补充了,但已经非常厉害了。

def is_winning_hand(hand):
    from collections import defaultdict

    if len(hand) != 14:
        return False

    # 统计每种牌的数量
    tile_count = defaultdict(int)
    for tile in hand:
        tile_count[tile] += 1

    # 检查牌的合法性(每种牌最多 4 张)
    for tile, count in tile_count.items():
        if count > 4:
            return False  # 非法牌型

    # 递归检查是否满足胡牌条件
    def can_form_melds(count):
        if sum(count.values()) == 0:
            return True

        # 尝试组成刻子(3张相同的牌)
        for tile in list(count.keys()):  # 使用 list 避免字典修改问题
            if count[tile] >= 3:
                count[tile] -= 3
                if can_form_melds(count):
                    return True
                count[tile] += 3

        # 尝试组成顺子(连续的3张牌)
        sorted_tiles = sorted(count.keys(), key=lambda x: ord(x))
        for i in range(len(sorted_tiles) - 2):
            tile1, tile2, tile3 = sorted_tiles[i], sorted_tiles[i + 1], sorted_tiles[i + 2]
            # 检查是否是连续的牌
            if (ord(tile1)-126983) // 9 == (ord(tile2)-126983) // 9 and (ord(tile1)-126983) // 9==(ord(tile3)-126983) // 9: #自己补充:同一种花色
              if ord(tile2) == ord(tile1) + 1 and ord(tile3) == ord(tile2) + 1:
                if count[tile1] >= 1 and count[tile2] >= 1 and count[tile3] >= 1:
                    count[tile1] -= 1
                    count[tile2] -= 1
                    count[tile3] -= 1
                    if can_form_melds(count):
                        return True
                    count[tile1] += 1
                    count[tile2] += 1
                    count[tile3] += 1

        return False

    # 尝试每一种可能的将牌
    for tile in list(tile_count.keys()):  # 使用 list 避免字典修改问题
        if tile_count[tile] >= 2:
            tile_count[tile] -= 2
            if can_form_melds(tile_count):
                return True
            tile_count[tile] += 2

    return False

# 示例测试
hand1 = "🀇🀇🀇🀈🀈🀈🀉🀉🀉🀙🀙🀙🀀🀀"  # 胡牌
hand2 = "🀇🀇🀇🀈🀈🀈🀉🀉🀉🀙🀙🀙🀙🀙"  # 非法牌型(5个一筒)
hand3 = "🀇🀇🀇🀇🀈🀈🀈🀉🀉🀉🀙🀙🀙🀀"  # 不胡牌
hand4 = "🀇🀇🀇🀈🀈🀈🀉🀉🀉🀎🀏🀐🀙🀙"  # 不胡牌
hand5 = "🀇🀇🀇🀇🀈🀉🀉🀉🀉🀐🀑🀒🀙🀙"  # 胡牌
print(is_winning_hand(hand1))  # 输出: True
print(is_winning_hand(hand2))  # 输出: False
print(is_winning_hand(hand3))  # 输出: False
print(is_winning_hand(hand4))  # 输出: False
print(is_winning_hand(hand5))  # 输出: True