"or" 有条件 Python
"or" conditional in Python
我想检查一个值是 -1 还是小于另一个值。
为了做到这一点,我做了以下事情:
def isValidWord(word, hand, wordList):
"""
Returns True if word is in the wordList and is entirely
composed of letters in the hand. Otherwise, returns False.
Does not mutate hand or wordList.
word: string
hand: dictionary (string -> int)
wordList: list of lowercase strings
"""
if word not in wordList:
return False
for k, v in getFrequencyDict(word).items():
if hand.get(k, -1) < v or hand.get(k, -1) == -1:
return False
return True
注意: getFrequencyDict(word)
returns 字母词出现频率的字典。
剩下的问题是:我在下面一行中犯错了吗?
if hand.get(k, -1) < v or hand.get(k, -1) == -1:
if any(c in someList for c in ("a", "á", "à", "ã", "â"))
这可以按照上面给定的方式来写。(注意它与你的问题不完全一样,只是想法)
如果你知道字典中的所有值都是正数,检查
if hand.get(k, -1) < v:
就够了。
在更通用的情况下,这似乎是使用 or
的正确方法(您的代码清楚地表明您检查了某些内容, 或 默认).
在这里使用 -1
作为默认值似乎是多余的,并且不允许推广到 hand
包含负值的情况。
if hand.get(k) is None or hand.get(k) < v:
...
或者,甚至 get
也可以被认为是多余的。要检查密钥是否存在,您可以简单地使用 in
.
if k not in hand or hand[k] < v:
...
只需使用设置。 词典 不需要这个。
设置支持差分运算
def isValidWord(word, hand, wordList):
"""
Returns True if word is in the wordList and is entirely
composed of letters in the hand. Otherwise, returns False.
Does not mutate hand or wordList.
word: string
hand: set of letters
eg: set(["u", "s", "a"] or set("usa")
wordList: set of strings
eg: set(["zeus", "osiris", "thor"])
"""
if word not in wordList:
return False
if len(set(word) - hand) != 0:
return False
return True
我想检查一个值是 -1 还是小于另一个值。
为了做到这一点,我做了以下事情:
def isValidWord(word, hand, wordList):
"""
Returns True if word is in the wordList and is entirely
composed of letters in the hand. Otherwise, returns False.
Does not mutate hand or wordList.
word: string
hand: dictionary (string -> int)
wordList: list of lowercase strings
"""
if word not in wordList:
return False
for k, v in getFrequencyDict(word).items():
if hand.get(k, -1) < v or hand.get(k, -1) == -1:
return False
return True
注意: getFrequencyDict(word)
returns 字母词出现频率的字典。
剩下的问题是:我在下面一行中犯错了吗?
if hand.get(k, -1) < v or hand.get(k, -1) == -1:
if any(c in someList for c in ("a", "á", "à", "ã", "â"))
这可以按照上面给定的方式来写。(注意它与你的问题不完全一样,只是想法)
如果你知道字典中的所有值都是正数,检查
if hand.get(k, -1) < v:
就够了。
在更通用的情况下,这似乎是使用 or
的正确方法(您的代码清楚地表明您检查了某些内容, 或 默认).
在这里使用 -1
作为默认值似乎是多余的,并且不允许推广到 hand
包含负值的情况。
if hand.get(k) is None or hand.get(k) < v:
...
或者,甚至 get
也可以被认为是多余的。要检查密钥是否存在,您可以简单地使用 in
.
if k not in hand or hand[k] < v:
...
只需使用设置。 词典 不需要这个。 设置支持差分运算
def isValidWord(word, hand, wordList):
"""
Returns True if word is in the wordList and is entirely
composed of letters in the hand. Otherwise, returns False.
Does not mutate hand or wordList.
word: string
hand: set of letters
eg: set(["u", "s", "a"] or set("usa")
wordList: set of strings
eg: set(["zeus", "osiris", "thor"])
"""
if word not in wordList:
return False
if len(set(word) - hand) != 0:
return False
return True