Advertisement
Woobinda

Min and Max, своя реализация

Jul 23rd, 2016
156
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.78 KB | None | 0 0
  1. """Собственная реализация встроенных функций min и max"""
  2.  
  3. from functools import reduce
  4.  
  5. def min(*args, **kwargs):
  6.     key = kwargs.get("key", None)
  7.     if key is not None:
  8.         if len(args) > 1:
  9.             arr = list(map(key, args))
  10.             value =  reduce(lambda x,y: x if x < y else y, map(key, args))
  11.             return args[arr.index(value)]
  12.         if len(args) == 1:
  13.             arr = list(map(key, *args))
  14.             value = reduce(lambda x,y: x if x < y else y, map(key, *args))
  15.             return args[0][arr.index(value)]
  16.                        
  17.     if len(args) > 1:
  18.         args = [arg for arg in args]
  19.         result = reduce(lambda x,y: x if x < y else y, args)
  20.         return result
  21.     result = reduce(lambda x,y: x if x < y else y, *args)
  22.     return result
  23.  
  24.  
  25. def max(*args, **kwargs):
  26.     key = kwargs.get("key", None)
  27.     if key is not None:
  28.         if len(args) > 1:
  29.             arr = list(map(key, args))
  30.             value =  reduce(lambda x,y: x if x > y else y, map(key, args))
  31.             return args[arr.index(value)]
  32.         if len(args) == 1:
  33.             arr = list(map(key, *args))
  34.             value = reduce(lambda x,y: x if x > y else y, map(key, *args))
  35.             return args[0][arr.index(value)]
  36.     if len(args) > 1:
  37.         args = [arg for arg in args]
  38.         result = reduce(lambda x,y: x if x > y else y, args)
  39.         return result
  40.     result = reduce(lambda x,y: x if x > y else y, *args)
  41.     return result
  42.  
  43.  
  44. if __name__ == '__main__':
  45.     #These "asserts" using only for self-checking and not necessary for auto-testing
  46.     assert max(3, 2) == 3, "Simple case max"
  47.     assert min(3, 2) == 2, "Simple case min"
  48.     assert max([1, 2, 0, 3, 4]) == 4, "From a list"
  49.     assert min("hello") == "e", "From string"
  50.     assert max(2.2, 5.6, 5.9, key=int) == 5.6, "Two maximal items"
  51.     assert min([[1, 2], [3, 4], [9, 0]], key=lambda x: x[1]) == [9, 0], "lambda key"
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement