From b3cbb121a44b6833d73afaba318040e371ccc32f Mon Sep 17 00:00:00 2001 From: BLUELOVETH Date: Thu, 1 Jun 2023 13:28:14 +0800 Subject: [PATCH] improve `max` and `min` --- python/builtins.py | 36 ++++++++++++++++++++++++++++++++---- 1 file changed, 32 insertions(+), 4 deletions(-) diff --git a/python/builtins.py b/python/builtins.py index 1d878a58..1d7e8f4d 100644 --- a/python/builtins.py +++ b/python/builtins.py @@ -16,11 +16,39 @@ def round(x, ndigits=0): def abs(x): return -x if x < 0 else x -def max(a, b): - return a if a > b else b +def max(*args): + if len(args) == 0: + raise TypeError('max expected 1 arguments, got 0') + if len(args) == 1: + args = args[0] + args = iter(args) + res = next(args) + if res is StopIteration: + raise ValueError('max() arg is an empty sequence') + while True: + i = next(args) + if i is StopIteration: + break + if i > res: + res = i + return res -def min(a, b): - return a if a < b else b +def min(*args): + if len(args) == 0: + raise TypeError('min expected 1 arguments, got 0') + if len(args) == 1: + args = args[0] + args = iter(args) + res = next(args) + if res is StopIteration: + raise ValueError('min() arg is an empty sequence') + while True: + i = next(args) + if i is StopIteration: + break + if i < res: + res = i + return res def all(iterable): for i in iterable: