2017-07-07 101 views
2

我有一個字典,其中字母對應於數字和字符串,並且如果每個字母出現在字符串中的次數等於或等於少於字典中與該字母相關的數字。當這個問題不那麼複雜並且沒有計算事件發生的限制時,我使用all(x in string for x in dictionary)。有沒有類似的簡潔的方式來測試這個基於字典中的int值?確定是否可以從另一個字符串中的字符子集創建一個字符串

編輯:道歉,這是我們正在看。如果我現在需要它,除非該字母出現的次數是<返回False 字符串中的字母任何實例都顯示爲手,一本字典關鍵

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 
    """ 
    if word.lower() in wordList and all(x in hand for x in word): 
     return True 
    else: 
     return False 

此代碼返回True =的該鍵的整數值。我已經非常混亂地完成了這個任務,並且想知道是否有辦法將這種特定級別的特徵合併到all方法或類似的簡潔方法中。

+0

請向我們提供樣本輸入和預期輸出。你的問題還不夠完整,無法給出明確的答案。 – abccd

+0

請發佈您的一些數據,以及您期望從中獲得什麼? –

+0

對不起,有一個帶有docstring的代碼塊 – Max

回答

1

從您的文檔字符串中,您試圖確定word是否可以使用hand中的字母組成。這是非常直接的使用collections.Counter。你甚至不需要製作hand字典。

def is_valid_word(word, hand, word_list): 
    wc, hc = Counter(word), Counter(hand) 
    return word.lower() in word_list and all(wc[k] <= hc[k] for k in wc) 

如果你想保持hand作爲一本字典,只需要使用hand代替hc線下決賽,而忽略它變成一個Counter

這在複雜性方面並不是最佳的,但是可以使用相同的總體思想來編寫一個好的算法。請注意,這比使用count更有效,因爲每個字符串只需要對每個唯一字母進行一次而不是一次迭代。

一個更有效的功能來檢查,這可能看起來像:

def is_partial_anagram(word, pool): 
    pool_counter = Counter(pool) 
    for c in word: 
     if not pool_counter[c]: 
      return False 
     pool_counter[c] -= 1 
    return True 

的複雜性在這裏是漸近相同,但將返回False越早當沒有比賽和避免建設者word一個Counter

1

如果我理解正確的你,你的hand字典形成,如:

hand = {"f": 1, "o": 2, "b": 1, "a": 1, "r": 1, "z": 0} 

而且你希望它匹配foobar但不bazz設置爲0,並至少有一個z。你可以做,使用str.count()喜歡:

def isValidWord(word, hand, wordList): 
    if word.lower() in wordList and all(hand.get(x, 0) >= word.count(x) for x in set(word)): 
     return True 
    else: 
     return False 

不是最有效的,但應該給你的想法。您可以使用以下方式對其進行測試:

hand = {"f": 1, "o": 2, "b": 1, "a": 1, "r": 1, "z": 0} # letters with their allowed counts 
word_list = ["foo", "bar", "baz"] # allowed words 

print(isValidWord("foo", hand, word_list)) # True 
print(isValidWord("bar", hand, word_list)) # True 
print(isValidWord("baz", hand, word_list)) # False 
+0

這可以通過省略'x in hand'然後使用'hand.get(x,0)'稍微簡化一些。 –

+0

@JaredGoguen - 公平點。更新。 – zwer

相關問題