Python字典值

2024-09-30 05:27:32 发布

您现在位置:Python中文网/ 问答频道 /正文

嗨,我刚刚开始学习如何编写程序,并有一个需要用Python编写的函数,这就是它背后的思想:

如果wordwordList中并且完全由手中的字母组成,则返回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的任何键折现。 我想(希望)那会起作用。在


Tags: 函数infalsetrueifis字母not
3条回答

pythonCounter类是您的朋友。您可以在python 2.7 and later中执行此操作:

from collections import Counter

def is_valid_word(hand, word, word_list):
    letter_leftover = Counter(hand)
    letter_leftover.subtract(Counter(word))
    return word in word_list and all(v >= 0 for v in letter_leftover.values())

然后:

^{pr2}$

如果没有您的代码,让我看看我是否理解您想要的:您试图查看给定单词是否可以使用hand中的字母拼写,就像用户对hand中的每个字母都有一个拼字块,是吗?在

就个人而言,我只需复制hand字典,然后允许对副本进行更改。像这样:

def is_valid_word(hand, word, wordlist):
    hand_cp = dict(hand)
    for letter in word:
        if hand_cp.get(letter):
            # The letter is in our hand, so "use it up".
            hand_cp[letter] = hand_cp[letter] - 1
        else:
            # The letter isn't in our hand, so the word isn't valid.
            return False

    # If we can make the word, now make sure it's a real word:
    # (If wordlist is long, you might want to sort it and do a real search)
    if word not in wordlist: 
        return False

    # We haven't found any reason to return False, so this is a valid word.
    return True

这样的怎么样:

def isValidWord(hand, word, word_list):
    if word not in word_list:
        return False
    for c in word:
        if c not in hand:
            return False
    return True

因为字符串是可编辑的,所以可以逐个检查。在

祝你好运

相关问题 更多 >

    热门问题