[英]how to change from list(list(tuple))) to list(set(tuple))
現在,當我運行我的代碼時,它返回 list(list(tuple)) 但我希望它是 list(set(tuple))。 當我試圖修復我的代碼時,會出現“TypeError: unhashable type”。 ** 我沒有使用導入方法,因為我的導師不允許我這樣做。
Hand = set[tuple[str, str]]
def all_card(): # 52 cards
rank: list[str] = ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K']
suit: list[str] = ['Club', 'Diamond', 'Heart', 'Spade']
my_card = []
for i in rank:
for j in suit:
my_card.append((i, j))
return my_card
def all_matches(cards, num):
if num == 0:
return [[]]
L = []
for i in range(0, len(cards)):
first = cards[i]
rem = cards[i + 1:]
all = all_matches(rem, num - 1)
for j in all:
L.append([first] + j)
print(len(L))
return L
def all_hands() -> list[Hand]: # 2,598,960
my_card = all_card()
return all_matches(my_card, 5)
print(all_hands())
all_matches()
應該返回List[Hand]
(= List[Set[Tuple[str, str]]]
),因為all_hands()
返回。
讓我們看看它現在返回了什么。 在遞歸基礎條件中,它是List[List]
:
if num == 0:
return [[]]
在遞歸代碼本身中,這也是List[List]
:
L = []
...
L.append([first] + j)
return L
我們想要編輯它以返回List[Set]
( List[Set[Tuple[str, str]]]
)。
在遞歸基礎條件下,我們可以很容易地:
if num == 0:
return [set()]
在遞歸代碼中,我們可以:
all = all_matches(rem, num - 1)
for j in all:
j.add(first)
L.append(j)
根據遞歸基本條件,現在all
都是List[Set]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.