2013-03-25 147 views
2
#iterative program to find the highest odd number 
m = sorted([a, b, c, d, e, f, g, h, j, k]) 
n = max(m) 
n = int(n) 
count = 10 
while n%2==0: 
    m=[m[:-1]] 
    n = max(m) 
    n = int(n) 
    count =-1 
if count==0: 
    print 'There are no odd numbers' 
else: 
    print str(n), 'is the largest odd number' 

我輸入包含奇數的變量,它給了我正確的答案,但是當我輸入所有偶數來滿足在'count==0'條件下,會出現以下錯誤:TypeError:int()參數必須是字符串或數字,而不是'list'

TypeError: int() argument must be a string or a number, not 'list'

我不明白爲什麼當有奇數輸入不會發生此錯誤。

+6

什麼了''的值,'B','C ','d','e','f','g','h','j'和'k'?另外,考慮到你正在排序列表,這個算法似乎不必要的複雜。 – 2013-03-25 21:01:28

+2

嘗試在循環中每次打印'm'和'n'的值;它應該可以幫助你看到你的錯誤在哪裏。也就是說,這是一種遍歷值列表的非正統方法。 – chepner 2013-03-25 21:10:51

回答

-3

如果只有偶數,則當您完全減少m時,while循環會產生此錯誤。在這種情況下,max(m)返回None,這不能是int的參數。爲了解決這個問題,你需要將你的while循環條件改爲更正確的。

然而,這並不是大多數人認爲的「pythonic」。理想的情況下爲您會用更喜歡for n in m[::-1]一個循環以相反的順序穿越m(或使用sortedreverse=True說法,只是for n in m

+2

'max(m)'不爲空序列返回'None';它引發了一個'ValueError'。而且,調用'int(None)'顯然不會給你一個'TypeError',它引用在'list'上調用'int'。 – abarnert 2013-03-25 21:19:51

2

如果你打印出什麼m是內循環,這將成爲很明顯的。或者你可能想用interactive visualizer或只是調試器來測試它。

假設您的值爲2, 4, 6, 8, 10, 12, 14, 16, 18, 20。排序後,你有:

m = [2, 4, 6, 8, 10, 12, 14, 16, 18, 20] 
n = max(m) = 20 
n = int(n) = 20 

max是沒用的,因爲排序是必須在列表中的最後一個值的定義(你似乎是依靠在你的循環反正) 。

而且int是一種誤導,它使它看起來像你的代碼將工作,即使數字是字符串而非數字,但它實際上不會,因爲sorted(和max)將把'10'小於'2',等等。

但這些都不是你的大問題。因爲你的第一個n甚至,你將進入循環,在循環的第一件事情是這樣的:

m=[m[:-1]] 

...這將做到這一點:

m = [[2, 4, 6, 8, 10, 12, 14, 16, 18]] 

所以,接下來的兩行這樣做:

n = [2, 4, 6, 8, 10, 12, 14, 16, 18] # the max of a 1-element list is that element 
n = int([2, 4, 6, 8, 10, 12, 14, 16, 18]) 

和繁榮,這是你的例外。

如果您想將m設置爲m的最後一個元素,請執行m = m[:-1]。圍繞它投擲那些額外的括號將m設置爲由一個元素組成的list,該元素本身是除m的最後一個元素之外的所有元素組成的列表。

請注意,儘管你在描述中說了什麼,「我輸入包含奇數的變量,它給了我正確的答案」,但事實並非如此。它只適用於你的最大值是奇數的情況,所以你從不首先進入循環。

修復此問題後,您的代碼實際上仍然中斷,但希望現在您知道如何自己調試此代碼。


同時,解決這個問題的pythonic方法是嘗試將高級英語描述直接轉換爲高級Python。我們如何找到m的最高奇數?

首先得到奇數號碼m

odds = (n for n in m if n % 2) 

(如果您創建一個odd功能,如果你,你可能更喜歡filter到發電機表達可能是更具可讀性。)

然後,以獲得最大的:

max_odd = max(odds) 

當然,你需要處理在沒有勝算的情況。你可以通過檢查if odd:來做到這一點。但蟒蛇,它通常是更好地請求原諒比許可,所以,這裏是你的整個程序:與m=[m[::-1]]發生

m = [a, b, c, d, e, f, g, h, j, k] 
odds = (n for n in m if n % 2) 
try: 
    print max(odds), 'is the largest odd number' 
except ValueError: 
    print 'There are no odd numbers' 
0

你的錯誤,因爲@abarnert指出。

這裏找到列表中的最大奇數一個簡單的方法:

m = sorted([int(n) for n in [a, b, c, d, e, f, g, h, j, k] if n%2==1]) 
# this makes a list of all ODD integers (converts them from strings) 
if len(m) != 0: 
    print str(max(m)), 'is the largest odd number' 
else: 
    print 'No odd integers inputted' 

進一步簡化成:

m = sorted([int(n) for n in [a, b, c, d, e, f, g, h, j, k] if n%2==1]) 
print (str(max(m)), 'is the largest odd number') if len(m)!=0 else 'No odd integers inputted' 
+0

爲什麼你同時使用'sorted'和'max'?爲什麼要檢查'if len(m)!= 0:'而不是更簡單,更pythonic'如果m:'(或者,甚至更好,只是'try:')?爲什麼要打印'str(max(m))'而不是'max(m)',因爲這就是'print'已經做的事情?而且,畢竟......這增加了什麼,這還不是我的答案? – abarnert 2013-03-25 21:52:37

相關問題