gpt4 book ai didi

python - 使用 Python 识别 'straight'(来自 Poker)

转载 作者:行者123 更新时间:2023-11-28 19:48:18 26 4
gpt4 key购买 nike

我正在编写一个 Python 函数,用于识别扑克中的“顺子”。我的代码有效并且会识别顺子,但只给我直子中的数字,而不是花色。此外,其余代码是用卡片的特定格式编写的,即 python 字典格式,因此我需要此函数也以这种格式返回卡片。

到目前为止我的代码:

cards_numbers=[11, 5, 6, 4, 2, 4, 3]
cards_dct={'11D': (11, 'D'), '5S': (5, 'S'), '6S': (6, 'S'), '4D': (4, 'D'), '2H': (2, 'H'), '4C': (4, 'C'), '3D': (3, 'D')}

def is_straight():
straight=False
numbers=set(numbers)
print numbers
sorted_numbers=sorted(numbers)
for i in range(len(sorted_numbers)):
if sorted_numbers[i]-sorted_numbers[i-1]==1 and sorted_numbers[i-1]-sorted_numbers[i-2]==1 and sorted_numbers[i-2]-sorted_numbers[i-3]==1 and sorted_numbers[i-3]-sorted_numbers[i-4]==1:
straight=True
highest_in_straight=sorted_numbers[i]
straight_numbers=range(highest_in_straight-4,highest_in_straight+1)
print straight_numbers
print self.cards_dct
for i in cards_dct.keys():
for j in numbers:
pattern=re.compile(str(j)+'[DSHC]')
print re.findall(pattern,i)

上面的代码将识别顺子,但我很难从字典中取回数字和花色。所以我的问题是,我怎样才能让我的代码返回一个字典,它只包含直线中的元素(不包括重复的 4)?

desired_outout={'5S': (5, 'S'), '6S': (6, 'S'), '2H': (2, 'H'), '4C': (4, 'C'), '3D': (3, 'D')}

最佳答案

像 Barmar 一样,我建议使用字典列表来代表你的手。

hand = [{'rank':10, 'suit':'Spade'}, {'rank':11, 'suit':'Heart'}, ...]

然后您可以通过创建一组排名(这将消除重复项)来检查是否有顺子。如果最高排名和最低排名之间的差值加上 1 等于三条的大小,并且三条是手牌的大小,那么您有顺子。这是对 pigeonhole principle 的缩减.

在 Python 中实现这个非常简单。

这里是为了验证它在给定顺子的情况下是否有效:

>>> hand = [{'rank':10, 'suit':'Spade'}, {'rank':11, 'suit':'Heart'}, {'rank':9, 'suit':'Spade'}, {'rank':12, 'suit':'Spade'}, {'rank':8, 'suit':'Spade'}]
>>> rank_set = { card['rank'] for card in hand }
>>> rank_set
set([8, 9, 10, 11, 12])
>>> is_straight = (max(rank_set) - min(rank_set) + 1) == len(hand) and len(rank_set) == len(hand)
>>> is_straight
True

现在检查它是否不是顺子:

>>> hand = [{'rank':10, 'suit':'Spade'}, {'rank':11, 'suit':'Heart'}, {'rank':9, 'suit':'Spade'}, {'rank':12, 'suit':'Spade'}, {'rank':7, 'suit':'Spade'}]
>>> rank_set = { card['rank'] for card in hand }
>>> is_straight = (max(rank_set) - min(rank_set) + 1) == len(hand) and len(rank_set) == len(hand)
>>> is_straight
False

现在让它成为一个函数:

def is_a_straight(hand):
rank_set = { card['rank'] for card in hand }
rank_range = max(rank_set) - min(rank_set) + 1
return rank_range == len(hand) and len(rank_set) == len(hand)

关于python - 使用 Python 识别 'straight'(来自 Poker),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34684816/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com