看板 Python 關於我們 聯絡資訊
感謝大家的幫忙,經過bibo9901和cutekid幫忙. 已解決了 import types def min(*args, **kwargs): key = kwargs.get("key", None) if len(args) == 1: args = args[0] it = iter(args) # get an iterator try: MinNo = next(it) # take the first value from the iterator except StopIteration: raise ValueError("max() called with no values") ? if key == None: for ii in it: if ii < MinNo: MinNo = ii else: min_keyval = key(MinNo) # initialize the minimum keyval for ii in it: keyval = key(ii) if keyval < min_keyval: # compare keyvals, rather than regular values min_keyval = keyval MinNo = ii return MinNo ? def max(*args, **kwargs): key = kwargs.get("key", None) if len(args) == 1: args = args[0] it = iter(args) # get an iterator try: MaxNo = next(it) # take the first value from the iterator except StopIteration: raise ValueError("max() called with no values") ? if key == None: for ii in it: if ii > MaxNo: MaxNo = ii else: max_keyval = key(MaxNo) # initialize the maxmum keyval for ii in it: keyval = key(ii) if keyval > max_keyval: # compare keyvals, great than regular values max_keyval = keyval MaxNo = ii return MaxNo ? if __name__ == '__main__': #These "asserts" using only for self-checking and not necessary for auto-testing assert max(3, 2) == 3, "Simple case max" assert min(3, 2) == 2, "Simple case min" assert max([1, 2, 0, 3, 4]) == 4, "From a list" assert min("hello") == "e", "From string" assert max(2.2, 5.6, 5.9, key=int) == 5.6, "Two maximal items" assert min([[1, 2], [3, 4], [9, 0]], key=lambda x: x[1]) == [9, 0], "lambda key" -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 59.124.107.139 ※ 文章網址: https://www.ptt.cc/bbs/Python/M.1501581196.A.149.html
bibo9901: def max(*args, key=None): 08/01 18:05
我在研究看看這篇 https://stackoverflow.com/questions/25249642/min-max-python-v3-implementation ※ 編輯: angleevil (59.124.107.139), 08/02/2017 08:54:15 ※ 編輯: angleevil (59.124.107.139), 08/02/2017 09:55:21