简体   繁体   English

从一手 7 张牌中提取对子

[英]extracting pairs from a hand of 7 cards

I am coding in Python to create a game of GoFish where instead of four of a kind, you are looking for pairs.我正在用 Python 编写代码来创建一个 GoFish 游戏,您正在寻找配对而不是四个游戏。 I wrote a code in python to find pairs in a hand of 7 cards.我在 python 中编写了一个代码来查找一手 7 张牌中的对。 The code gives a list of all pairs (so it is a list of list).代码给出了所有对的列表(所以它是一个列表列表)。 Since I am new to Python, I am wondering if there is a more efficient way to achieve what my code does.由于我是 Python 新手,我想知道是否有更有效的方法来实现我的代码的功能。

Here is the code I wrote.这是我写的代码。 Eventually, it will become a function inside a class.最终,它将成为类中的一个函数。

#hand = ['D2', 'S1', 'D3', 'H1', 'C1', 'H5', 'D5']
#hand = ['D1', 'S1', 'S2', 'H2', 'C1', 'H5', 'D5']
#hand = ['D1', 'S1', 'S2', 'H1', 'C1', 'H5', 'D5']
hand = ['D1', 'S1', 'C1', 'H1', 'C2', 'H2', 'D5']
#hand = ['D2', 'S1', 'C3', 'H4', 'C5', 'H6', 'D7']

list_of_pairs = []
i=0
while i < len(hand):
    current_pos = i
    for k in range(i+1, len(hand)):
        card_1 = hand[i]
        card_2 = hand[k]
        if card_1[-1:] == card_2[-1:]:
            pair_2 = hand.pop(k)
            pair_1 = hand.pop(i)
            pair = [pair_1, pair_2] 
            list_of_pairs.append(pair)
            i = current_pos - 1
            break
    i +=1 

print(f"List of pairs is {list_of_pairs}")
print(f"Left over hand is {hand}")
hand = [1,1,2,2,3,4,5,6,7,7,8,9,9]
hand_set = set()
pairs = set()
for card in hand:
    if card in hand_set:
        pairs.add(card)
    else:
        hand_set.add(card)

if tow pairs of same card is possible如果两对相同的卡是可能的

from collections import Counter
hand = [1,1,1,1,2,2,3,3,4,4,5,5,6,7,8,9,9,9,9]
card_counter = Counter()
for card in hand:
    card_counter[card]+=1

pairs = []
for k in card_counter:
    for i in range(int(card_counter[k]/2)):
        pairs.append([k,k])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM