我必须编写一个函数,如果你只能使用myLetters中的字母拼出myWord,则返回bool值为True,如果不能,则返回bool值False。
要做到这一点,我需要我的letterPoints字典:
global letterPoints
letterPoints = {"A": 1, "B": 3, "C": 3, "D": 2, "E": 1, "F": 4, "G": 2, "H": 4, "I": 1, "J":8, "K": 5, "L": 1, "M": 3, "N": 1, "O": 1, "P": 3, "Q": 10, "R": 1, "S": 1, "T": 1, "U": 1, "V": 4, "W": 4, "X": 8, "Y": 4, "Z": 10}
def canWeMakeIt(myWord, myLetters):
canMake = True
letterPoints= list(myLetters)
length=len(myWord)
for i in range(length):
i=i+1
letter=myWord[i]
if letter not in letterPoints:
canMake = False
else:
letterPoints.remove(letter)
return canMake
答案 0 :(得分:1)
这是你的功能
def canWeMakeIt(my_word, letters):
allowed = list(letters):
for i in my_word:
if i not in allowed:
return False
return True
#NOTICE HOW YOU MUST CALL IT TO DO SOMETHING
print(canWeMakeIt("cat","tack"))
现在让我们分析您的代码:
基本上它的工作是这样的:
def canWeMakeIt(myWord, myLetters):
canMake = True
letterPoints = list(myLetters)
length = len(myWord)
for i in range(length):
letter = myWord[i]
if letter not in letterPoints:
canMake = False
return canMake
print(canWeMakeIt("cat","tac"))
你注意到区别;)
答案 1 :(得分:0)
您可以计算word
到collections.Counter
中的字母数,然后将这些字母和出现次数与您传递给该函数的字典available_letters
的值和值进行比较:
from collections import Counter
def can_we_make_it(word, available_letters):
letter_counter = Counter(word.upper())
for letter, count in letter_counter.items():
if count > available_letters.get(letter, 0):
return False
return True
在您提供的示例中,传递给函数的字典的键是大写的。我在这里做了同样的假设,即available_letters
的键是大写字母。值得注意的是,由于Python区分大小写,因此有必要将word
转换为大写字母到word.upper()
,以避免在KeyError
包含小写时出现word
异常字母。
还值得指出的是,当count > available_letters.get(letter, 0)
包含不存在的字母时,您应检查条件count > available_letters[letter]
而不是KeyError
以避免word
例外available_letters
。
演示:
In [275]: can_we_make_it('one', {'O': 1, 'N': 1, 'E': 1})
Out[275]: True
In [276]: can_we_make_it('Zone', {'O': 1, 'N': 1, 'E': 1})
Out[276]: False
In [277]: can_we_make_it('Zone', {'O': 1, 'N': 1, 'E': 1, 'Z': 1})
Out[277]: True
In [278]: can_we_make_it('ozone', {'O': 1, 'N': 1, 'E': 1, 'Z': 1})
Out[278]: False
In [279]: can_we_make_it('ozone', {'O': 2, 'N': 1, 'E': 1, 'Z': 1})
Out[279]: True
注意:我冒昧地改变了标识符,使它们变得更加pythonic。