如何在Python中确定扑克牌中的直(序列)

如何在Python中确定扑克牌中的直(序列),python,sequence,playing-cards,Python,Sequence,Playing Cards,在python中,我有一个扑克手的分数跟踪器 可能的信用卡等级: A23456789TJQK 3张或以上的直道每张牌得1分。4张牌的例子给你4分 所以我有一个分数: score = 0 一个已排序的字符串列表(因此我不必担心列表末尾的牌与开头之间有直线),表示我特定手牌的牌列: L4 ['6', '8', '8', '9', 'T'] # Note: 8, 9, T is a straight. So I want to add 3 to score 但我如何才能确定我是否有一个直的 到目前

在python中,我有一个扑克手的分数跟踪器

可能的信用卡等级:

A23456789TJQK

3张或以上的直道每张牌得1分。4张牌的例子给你4分

所以我有一个分数:

score = 0
一个已排序的字符串列表(因此我不必担心列表末尾的牌与开头之间有直线),表示我特定手牌的牌列:

L4
['6', '8', '8', '9', 'T']
# Note: 8, 9, T is a straight. So I want to add 3 to score
但我如何才能确定我是否有一个直的

到目前为止,我所尝试的:

我试着将字符串转换成整数,但接下来如何处理T、J、K、Q和A?它们不是数字

使用字符串我得到一个错误:

for i in range(len(L4) - 1):
   if(L4[i] is L4[i + 1] + 1):
      sC = sC + 1
if(sC >= 3):
   score += sC


L4
['6', '8', '8', '9', 'T']
Traceback (most recent call last):
  File "myFile.py", line 66, in <module>
    if(L4[i] is L4[i + 1] + 1):
TypeError: must be str, not int
适用于范围内的i(len(L4)-1):
如果(L4[i]是L4[i+1]+1):
sC=sC+1
如果(sC>=3):
分数+=sC
L4
['6','8','8','9','T']
回溯(最近一次呼叫最后一次):
文件“myFile.py”,第66行,在
如果(L4[i]是L4[i+1]+1):
TypeError:必须是str,而不是int

我应该将它们转换为整数还是尝试其他方法?提前感谢您的帮助。

您可以找到当前手牌的所有子字符串,并过滤结果以查找以
1
增量排序的子字符串:

def stringify_result(f):
  def wrapper(_d):
    cards = {10:'T', 11:'J', 12:'Q', 13:'K'}
    return list(map(lambda x:cards.get(x, str(x)), f(_d)))
  return wrapper

@stringify_result
def has_straight(d):
  cards = {'J': 11, 'K': 13, 'T': 10, 'Q': 12}
  subs = list(filter(None, [d[b:i] for i in range(len(d)+1) for b in range(len(d)+1)]))
  possibilities = list(filter(lambda x:all(x[i+1] - x[i] == 1 for i in range(len(x)-1)), [[int(cards.get(b, b)) for b in i] for i in subs]))
  return [] if not possibilities else max(possibilities, key=len)

straight = has_straight(['6', '8', '8', '9', 'T'])
score = len(straight)
输出:

['8', '9', 'T']
3
(2, [8, 9, 10])
(4, [4, 5, 6])
编辑:要考虑多次运行,可以使用
itertools.groupby

import itertools
def has_straight(d):
   cards = {'J': 11, 'K': 13, 'T': 10, 'Q': 12}
   mutated_cards = list(map(lambda x:int(cards.get(x, x)), d))
   _grouped = [list(b) for _, b in itertools.groupby(mutated_cards)]
   subs = list(filter(None, [_grouped[b:i] for i in range(len(_grouped)+1) for b in range(len(_grouped)+1)]))
   final_filtered = list(filter(lambda x:all(x[i+1][0] - x[i][0] == 1 for i in range(len(x)-1)), subs))
   new_subs = [] if not final_filtered else max(final_filtered, key=lambda x:sum(len(i) for i in x))
   return sum(len(i) for i in new_subs if len(i) > 1), list(map(lambda x:x[0], new_subs))

print(has_straight(['6', '8', '8', '9', 'T']))
print(has_straight(['4', '4', '5', '5', '6']))
输出:

['8', '9', 'T']
3
(2, [8, 9, 10])
(4, [4, 5, 6])

使用字典,将T、J、K、Q、a翻译成数字。你的问题不清楚。
'6'、'7'、'8'、'9'==1直4或2直3
?因为我得到了更多的分数,将其计算为3的2直,这是使用字符串表示牌的许多问题之一。使用从头开始的数字,仅转换为字符串进行输出。别忘了你还得去百老汇的特例:1-10-11-12-13。嘿,谢谢你的帮助。您知道我如何修改此代码以考虑多次运行吗?例如,我应该从
['6','8','8','9','T']
中得到2次运行,因为有两个8表示两个8,9,T序列。另外,例如:当我经过时,我只会直接从has回来。但我可以看到我应该找回的4分。谢谢你的时间。