2014-01-28 33 views
0

我必須調試功能是:調試固定的功能,例如THST第二工作正常

def buggy_contains(current, new): 
    for mail in current: 
     if mail == new: 
      return True 

    return False 

我必須解決上述功能,使得所述第二功能正常工作:

def add_new_mail(existing, new): 
    if buggy_contains(existing, new): 
     return # already exists nothing to do. 
    existing.append(new) 

每當我調用函數時,它會將每封郵件附加到列表並返回列表,但每當傳遞一個帶有大寫字母的類似郵件時,它應該將其視爲同一郵件,但它不是.Ex:add_new_mail(郵件, 「[email protected]」)和add_new_mail(郵件「[email protected]」)應該被視爲相同但它還在計算第二封郵件。 我試圖通過更改第二個函數來完成它,但只有第一個函數應該被修復。如何修復它?

回答

0

Python在字符串比較中區分大小寫。

buggy_contains,使用方法:

if mail.lower() == new.lower(): 

和問題將得到解決。

因此函數應該是這樣的:

def buggy_contains(current, new): 
    for mail in current: 
     if mail.lower() == new.lower(): 
      return True 

    return False 
1

如果你不介意的話,我們完全可以替代現有的列表爲字典,這將節省大量的時間,你很多時候你的列表較大。

def add_new_mail(existing, new): 
    if not existing.get(new.lower(), None): 
     existing[new.lower()] = True 
    else: 
     print 'Exists: %s' % new 

existing = dict() 
for i in ['[email protected]', '[email protected]', '[email protected]']: 
    add_new_mail(existing, i) 

print existing 

輸出:

Exists: [email protected] 
{'[email protected]': True, '[email protected]': True}