2015-06-14 70 views
-2

我需要編寫一個函數來打印三個輸入參數中最大的奇數。從函數中的三個參數中找出最大的奇數[Python]

這是我的代碼。

def oddn(x,y,z): 
odd_number_keeper = [] 
for item in x,y,z: 
    global odd_number_keeper 
    if item % 2==1: 
     odd_number_keeper = [item] 
     return max(odd_number_keeper) 
    else: 
     print 'No odd number is found' 

我的代碼似乎不起作用。任何想法如何我可以修改此代碼?將需要

回答

2

一些改動:

def oddn(x,y,z): 
    odd_number_keeper = [] 
    for item in [x,y,z]: 
     if item % 2==1: 
      odd_number_keeper.append(item) 
    if not odd_number_keeper: 
     print 'No odd number is found' 
     return 
    return max(odd_number_keeper) 

遍歷值xyz和奇數添加到odd_number_keeper。如果有任何數字,則返回此奇數列表中元素的max()。如果沒有奇數,則打印該消息並返回(沒有結果,因爲沒有數字要返回)。

1

你必須先過濾所有的奇數號碼,然後調用max

def oddn(x,y,z): 
    odd_numbers = [item for item in (x,y,z) if item%2==1] 
    return max(odd_numbers) 

或簡稱:

def oddn(*numbers): 
    return max(x for x in numbers if x % 2 == 1) 

也這是不好的做法,如果你想打印一些消息出現錯誤:

def oddn(*numbers): 
    try: 
     return max(x for x in numbers if x % 2 == 1) 
    except ValueError: 
     print 'No odd number is found' 
     return None 
+0

謝謝Daniel。但是,如何在代碼中打印「沒有找到奇數」? – Yousuf

+0

@DumbCoder:見編輯。 – Daniel

0

您未找到列表中最大的奇數,而是您正在查找第一個奇數並返回。問題是在線路 -

odd_number_keeper = [item] 
return max(odd_number_keeper) 

你首先需要追加項目列表,使得odd_number_keeper列表僅與該項目的insteading。

其次,return語句應該在函數的結尾,而不是在for循環中。

你需要一個代碼類似 -

def oddn(x,y,z): 
    odd_number_keeper = [] 
    for item in x,y,z: 
     if item % 2==1: 
      odd_number_keeper.append(item) 
    return max(odd_number_keeper) 
+0

謝謝,夥計。你的建議幫助我清楚地理解了這一點。 – Yousuf

0

您重置odd_number_keeper每次。你可能意味着

odd_number_keeper += [item] 

另外,returnprint應該是在(外)for循環的結束。 (請修復縮進以使其更清晰)。

+0

謝謝,曼爲你的提示。 – Yousuf

0

使用過濾器解決它。以pythonic方式進行。

def oddn(a, b, c): 
    final = [] 
    final.append(a) 
    final.append(b) 
    final.append(c) 
    result = filter(lambda x: x % 2 != 0, final) 
    return max(result) 
相關問題