【问题标题】:How can I make my code take in input as a set of tuples and still return the same answer?如何让我的代码将输入作为一组元组接收并仍然返回相同的答案?
【发布时间】:2022-01-15 19:54:01
【问题描述】:

于是我尝试写了两段代码,其中一段试图找出一个代码序列是否为fourz

fourz 基本上可以查看一张卡片是否有 4 个相同的第一个字符和一个不同的字符。

例如,

fourz(['3S', '3D', '3C', '3H', '5S']) returns True because there are 4 3 and one 5
fourz(['4S', '3D', '3C', '3H', '5S']) returns False because there are only three 3, and one 4 and one 5.

所以现在我有了这个代码:

def is_four_of_a_kind(h):
    h = list(h)
    values = [i[0] for i in h]
    card_order_dict = {'2': 2, '3':3, '4':4, '5': 5, '6':6, '7':7,
                       '8':8, '9':9,'T':10, 'J':11, 'Q':12, 'K':13, 'A':14 }
    count = 1
    rank_values = [card_order_dict[i] for i in values]
    rank_values = sorted(rank_values)

    for i in range(1,len(rank_values)):
        if rank_values[i] == rank_values[0]:
            count += 1
    if count == 4:
        return True
    else:
        return False

当代码是 list 时,此代码正确返回输出,但当它是 元组集

时它不起作用

因此,如果我的代码是这样的fourz({('3S', '3D', '3C', '3H', '5S')},我的代码将无法正常工作..

我必须对我的代码进行哪些更改才能使其正常工作?

【问题讨论】:

    标签: python list set tuples


    【解决方案1】:

    这是因为您在集合内定义了一个元组。因此,当您将其转换为列表时,列表中将只有一个元素。

    为了使您的代码正常工作,您可以对转换为列表的功能进行简单的更改。

    def is_four_of_a_kind(h):
    if type(h) == set:
        for i in h:
            h = list(i)
    else:
        h = list(h)
    
    values = [i[0] for i in h]
    card_order_dict = {'2': 2, '3':3, '4':4, '5': 5, '6':6, '7':7,
                       '8':8, '9':9,'T':10, 'J':11, 'Q':12, 'K':13, 'A':14 }
    count = 1
    rank_values = [card_order_dict[i] for i in values]
    rank_values = sorted(rank_values)
    
    for i in range(1,len(rank_values)):
        if rank_values[i] == rank_values[0]:
            count += 1
    if count == 4:
        return True
    else:
        return False
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-11
      • 1970-01-01
      • 2015-05-18
      • 1970-01-01
      相关资源
      最近更新 更多