【问题标题】:How can I make my output return True or False when the input is a set of tuples?当输入是一组元组时,如何使输出返回 True 或 False?
【发布时间】: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 元组。会不会不止一个,如果没有,为什么要把元组放在一个集合中?

标签: python tuples


【解决方案1】:

您传递给函数的结构,例如 {('AS', 'AD', 'CC', 'CH', 'CS')},是一组元组,因此您还需要在 for 循环内有一行转换为列表:

for hands in h:
    hands = list(hands)

【讨论】:

    【解决方案2】:
    h = list(h)
    

    只是将集合更改为列表。如果您想更改集合中的单个元组,您需要这样做

    h = [list(hands) for hands in h]
    

    它不适用于元组的原因是元组不能被修改。这样做是为了提高元组的性能,因此元组没有弹出功能。

    【讨论】:

      猜你喜欢
      • 2022-01-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-05
      • 2016-11-25
      • 2020-08-14
      • 1970-01-01
      相关资源
      最近更新 更多