【发布时间】:2021-12-11 06:46:07
【问题描述】:
所以我正在尝试分析我的 元组集 h 并查看该集合中的 x 是否分别有两对 2 个元素和 3 个元素。
所以就像每个第一个字符一样,必须有 3 个相同的字符和 2 个相同的字符...
它们必须是连接的,比如如果有 3 A 和 2 C,顺序只能是 AAACC 或 CCAAA,不能是 CACAA 或 ACCAA 等
例如,
{('AS', 'AD', 'CC', 'CH', 'CS')} returns True because there are 3 C and 2 A
{('AS', 'AD', 'SC', 'SH', 'CS')} returns False because there are 2 A, 2 S and one C.
{('CS', 'CD', 'CC', 'AH', 'AS')} returns True because there are 3 C and 2 A
{('AS', 'DD', 'AC', 'AH', 'DS')} returns False because even though there are 3 A and 2 D, they are not following each other as indicated by the bold text above
这是我对代码的尝试
def is_full_house(h):
h = list(h)
for hands in h:
bools = True
last_count = 1
last_item = hands.pop(0)[0]
while hands:
item = hands.pop(0)
if (item[0] == last_item):
last_count += 1
if (last_item != item[0]):
if (last_count == 2) or (last_count == 3):
bools = True
else:
bools = False
break
last_item = item[0]
return (bools)
但是,我的代码只有当它是一个列表时才有效……当我放入一组元组时,它不起作用……
我应该进行哪些更改才能使其正常工作?
编辑:我的输出显示错误,元组没有属性 pop。但是,我已经尝试将它转换为一个列表,如 h = list(h) 所示,但它仍然不起作用
【问题讨论】:
-
您可以使用索引访问像数组一样的元组。尝试
hands[0]作为元组中的第一个元素。 -
你所有的例子都是一组完全 one 元组。会不会不止一个,如果没有,为什么要把元组放在一个集合中?