嗨,我刚刚开始学习如何编写程序,并有一个需要用Python编写的函数,这就是它背后的思想:
如果word
在wordList
中并且完全由手中的字母组成,则返回True
。否则,返回False
。不会改变手或单词表。在
有一个函数可以用来检查用户输入的单词中字母的频率,这是一个转换成dict的函数,我尝试过用各种方法使用iteritems,但是没有用,我被那些有重复字母的单词卡住了,当我在用户手中没有这封信的两个条目时,它们会被当作真的返回。在
抱歉,如果不清楚,我两周前才开始。 有什么建议就好了我已经在这上面呆了很长时间了!在
def isValidWord(hand,word,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
"""
wordC = getFrequencyDict(word)
handC = dict.copy(hand)
if word not in wordList:
return False
for c in word:
if c not in hand:
return False
for k,v in wordC.iteritems():
if k in hand and v > 1:
handC[k] -= 1
基本上,我的下一步是想弄清楚如何将word和handC进行比较,并将值为0的任何键折现。 我想(希望)那会起作用。在
python
Counter
类是您的朋友。您可以在python 2.7 and later中执行此操作:然后:
^{pr2}$如果没有您的代码,让我看看我是否理解您想要的:您试图查看给定单词是否可以使用
hand
中的字母拼写,就像用户对hand
中的每个字母都有一个拼字块,是吗?在就个人而言,我只需复制
hand
字典,然后允许对副本进行更改。像这样:这样的怎么样:
因为字符串是可编辑的,所以可以逐个检查。在
祝你好运
相关问题 更多 >
编程相关推荐