如果 word 在 word_list 中并且完全由手中可用的字母組成,則函式 is_valid_word 應該回傳 True。否則,回傳 False。它不會改變 hand 或 word_list。
def get_frequency_dict(sequence): #helper function
freq = {}
for x in sequence:
freq[x] = freq.get(x, 0) 1
return freq
def is_valid_word(word, hand, word_list):
word = word.lower()
handc = hand.copy()
freq = get_frequency_dict(word)
if word in word_list:
for e in word:
if e in handc and handc[e] >= freq[e]:
pass
else:
return False
return True
else:
return False
print(is_valid_word('caapture',
{'c': 3, 'a': 1, 'p': 2, 'e': 1, 't': 1, 'u': 1},
['caapture', 'hello'])) #example
我注意到,如果我在代碼中使用return True而不是pass,它不會讀取word. 我明白為什么。沒有其他方法可以實作該功能pass嗎?
也可以避免多個 else 陳述句嗎?
uj5u.com熱心網友回復:
擺脫第一個else否定條件的變化
if e in handc and handc[e] >= freq[e]:
pass
else:
return False
至
if e not in handc and handc[e] < freq[e]:
return False
第二個else你可以擺脫它,重寫
if word in word_list:
...
return True
else:
return False
作為
if word in word_list:
...
return True
return False
由于函式總是在 if 陳述句內部時提前回傳(return True因為單詞不在單詞表中。即,我們無需寫出 else 即可獲得 else 的行為。
也代替
freq = get_frequency_dict(word)
您可以使用計數器。
freq = collections.Counter(word)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/516126.html
標籤:Python功能if 语句
上一篇:如何使用jquery、ajax和html檔案進行無限滾動
下一篇:將列添加到聚合表時的NaN
