如何在python中使用check函数?

2024-05-14 03:11:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前正在完成一个围捕程序和python,正在努力确定如何“检查”一只手上是否有4张相同等级的牌(ace、2等),并将其移除。我目前的代码如下:

def check(hand, score):

   for i in range(len(hand)- 1):

    j = hand[i]

    if j == 4:

      print("you have completed a set :)")

      for j in range(4):

        hand.remove[j]

    score += 1

  else:

    print("no sets have been found ☹")

有什么建议吗


Tags: 代码in程序youforlenifdef
1条回答
网友
1楼 · 发布于 2024-05-14 03:11:55

您可以使用set在已检查的手牌中获得唯一的卡,然后计算出现的次数:

def check(hand):
    score = 0
    for card in set(hand):
        count = len([x for x in hand if (x == card)])
        if count >= 4:
            score += 1
            print("you have completed a set of '{}' :)".format(card))
            for j in range(count):
                hand.remove(card)
    if score == 0:
        print("no sets have been found ☹")

    return score

h1 = [i for i in range(12)]
h2 = [i for i in (['A', 'A', 'A', 'A', 7, 7, 7, 'J'] + h1)]

print(h1)
print('Score: {}\n'.format(check(h1)))

print(h2)
print('Score: {}'.format(check(h2)))

结果:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
no sets have been found ☹
Score: 0

['A', 'A', 'A', 'A', 7, 7, 7, 'J', 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
you have completed a set of '7' :)
you have completed a set of 'A' :)
Score: 2

相关问题 更多 >