def chooseBest(s):
if len(s) == 2:
c = cmp(s[0], s[1])
if c == -1 or c == 0:
return s[0]
elif c == 1:
return s[1]
else:
return chooseBest(s[1:])
其中's'是可比值的列表。遞歸比較,你能指出我的錯誤嗎?
def chooseBest(s):
if len(s) == 2:
c = cmp(s[0], s[1])
if c == -1 or c == 0:
return s[0]
elif c == 1:
return s[1]
else:
return chooseBest(s[1:])
其中's'是可比值的列表。遞歸比較,你能指出我的錯誤嗎?
如果你試圖遞歸找到可比值列表的最大元素,這裏應該怎麼做:
def chooseBest(s):
if not s:
return None
best = chooseBest(s[1:])
return s[0] if s[0] > best else best
或者更短:
def chooseBest(s):
return max(s[0], chooseBest(s[1:])) if s else None
無論哪種方式,它適用於內置的可比數據類型。如果由於某種原因,你需要將它與您定義的類型比較,不要忘記,使其與None
媲美:
chooseBest([1, 2, 5, 3, 4])
=> 5
chooseBest(['a', 'b', 'z', 'c', 'd'])
=> 'z'
想想chooseBest([x,y,z])是否可以返回x。
這裏有什麼問題嗎? –
當你問一個問題時,請明確地寫下你的意圖。你想做什麼?在什麼情況下? – Elazar
根據那裏的代碼,似乎目的是在序列中找到最少的元素。 – morningstar