2017-02-11 368 views
1

當前正在進行分配並且有點卡住。尋求一些幫助來解決這個問題。我試圖嘗試一個函數,該函數需要用戶輸入的雜誌和贖金兩個值。如果可以在雜誌中找到贖金中的字符,我想返回它,否則如果在雜誌字符串中找不到贖金字符串,則返回false。贖被分成一個字典{鍵,vaue}因此,例如,用戶輸入:將字符串的字符與字典進行比較python

輸入雜誌:你好

輸入贖:你好

{ 'H':1, 'E':如圖1所示, 'L':2, 'O':1}

{ 'H':1, 'E':1, 'L':1, 'O':1}

這應返回true,但它返回false,因爲它不計入'hello'中的第二個'l'。我究竟做錯了什麼?

def compare(magazine, ransom): 
matches = {} 
for ch in ransom: 
    if ch in magazine: 
     if ch in matches: 
      matches[ch] += 1 
     else: 
      matches[ch] = 1 

if ransom in matches: 
    return True 
else: 
    return False 
+0

'贖在matches'檢查是否全詞贖是在屬於字典'密鑰{ 'H':1, 'O':1, 'L':2, 'E':1} '。字典中的「somethin」只有在提供字符串時纔會返回「True」,這是提供的字典中的一個關鍵字。 – MaLiN2223

回答

1

如果贖金比賽:

首先,這種比較似乎是錯誤的,贖金被認爲是其通過用戶輸入的字符串相匹配,應該是一本字典。

在您的代碼:

ransom: 'hello' 
matches: {'h': 1, 'e': 1, 'l': 2, 'o': 1} 

所以,你如果條件將是這樣的:

if 'hello' in {'h': 1, 'e': 1, 'l': 2, 'o': 1}: 
    # this line will not be executed 

它應該是這樣的:

if 'h' in {'h': 1, 'e': 1, 'l': 2, 'o': 1}: 
    # this line will be executed 

的一個好方法比較:

# 1. Processing ransom 
{'h': 1, 'e': 1, 'l': 2, 'o': 1} 
# 2. Processing magazine 
{'h': 2, 'e': 3, 'l': 2, 'o': 1} 
# 3. Comparing each character and counts of both one by one in a for-loop 

贖金被分成字典{鍵,vaue}

注:這個假設的方式可能是錯誤的。字典比較將忽略字符串的順序,並且比較字符一個接一個地計數而沒有順序。

# Those examples could give unexpected answers 
compare('hello there', 'olleh') 
compare('hello there', 'olleeeh') 
相關問題