Python - 整理代码 - 循环和递归特性

标签 python loops recursion

我有以下代码可以正常工作。然而,在我学习的同时,我正在努力寻找不断改进我的代码的方法。 是否有可能以任何方式使下面的代码更整洁?

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
    """
    x=''
    if word in wordList:
        x=True
    else:
        x=False
    #dont mutate the hand so copy
    hand2=hand.copy()
    for letter in word:
        if letter in hand2.keys():
            hand2[letter]-=1
            if hand2[letter]<0:
                x=False
                break

        else:
            x = False
    return x

运行代码:

hand = {'r': 1, 'a': 3, 'p': 2, 'e': 1, 't': 1, 'u':1}

word = "rapture"

wordList = ['rapture','alex']
isValidWord(word, hand, wordList)

最佳答案

使用 all 和一个 Counter:

from collections import Counter

def isValidWord(word, hand, wordList):
    wc = Counter(word)
    return word in wordList and all(wc[c] <= hand.get(c, -1) for c in wc)

如果您有非常大的单词列表,请考虑使用集合代替 O(1) 查找时间。

关于Python - 整理代码 - 循环和递归特性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35298084/

相关文章:

python - 将负 y 轴转换为正 (matplotlib)

python - 使用 Django auth 用户模型作为外键和反向关系

Java ArrayList ArrayIndexOutOfBoundsException

java - 将 int 转换为 int 数组

python - 在 Pandas 中循环并应用正则表达式

c++ - 这段代码是否遵循递归的定义?

Python C API : How to get PyRun_String with Py_eval_input to use imported modules?

python - 为多个 celery worker 和线程正确设置 Flask-SQLAlchemy

c# - 在 C# 中使用递归

c++ - 递归中需要双指针