我的python代码未正确编译。这是问题: 返回所提供的Set手中的套数。
Parameters:
cards (list(str)) a list of twelve cards as 4-bit integers in
base 3 as strings, such as ["1022", "1122", ..., "1020"].
Returns:
(int) The number of sets in the hand.
Raises:
ValueError: if the list does not contain a valid Set hand, meaning
- there are not exactly 12 cards,
- the cards are not all unique,
- one or more cards does not have exactly 4 digits, or
- one or more cards has a character other than 0, 1, or 2.
这是我的代码:
def count_sets(cards):
num_sets = len(cards)
for i in range(num_sets):
for j in range(num_sets):
cards_test = cards[i]
for m in range(len(cards_test)):
if num_sets != 12:
raise ValueError("there are not exactly 12 cards,")
elif i != j:
if cards_test == cards[j]:
raise ValueError("the cards are not all unique,")
elif len(cards_test) != 4:
raise ValueError("one or more cards does not have exactly 4 digits, or")
elif cards_test[m] != 0 or cards_test[m] != 1 or cards_test[m] != 2: #----the problem is here
raise ValueError("one or more cards has a character other than 0, 1, or 2.")
else:
return num_sets
print(count_sets(["1111", "2222", "1212", "1222", "1112", "0011", "0022", "2211", "1010", "0000", "1221", "0220"]))
答案 0 :(得分:0)
此行是错误的:
elif cards_test[m] != 0 or cards_test[m] != 1 or cards_test[m] != 2:
应该是:
elif cards_test[m] != 0 and cards_test[m] != 1 and cards_test[m] != 2:
表示如果cards_test[m]
不为0且不为1且不为2,则引发Error。
一种更好的写法如下:
elif not cards_test[m] in "012":