繁体   English   中英

遍历字符串列表的问题

[英]Issues Iterating Through List of Strings

我的 python 代码编译不正确。 这是问题:返回提供的 Set 手中的 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"]))

这一行是错误的:

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,则引发错误。

更好的写法如下:

elif not cards_test[m] in "012":

暂无
暂无

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

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