2017-02-22 4 views
0
def min(*args, **kwargs): 
    key = kwargs.get("key", None) 
    if len(args) == 1: 
     vars = args[0] 
    else: 
     vars = args[:] 
    ans = None 
    for arg in vars: 
     if ans is None: 
      ans = arg 
      continue 
     if key is not None: 
      if key(arg) < key(ans): 
       ans = arg 
     else: 
      if arg < ans: 
       ans = arg 
     return ans 

print(min("hello")) 
print(min([[1,2], [3, 4], [9, 0]], key=lambda x: x[1])) 

誰かが私にこのコードのこの部分を説明できますか?Pythonの場合キー(arg)<キー(ans)

for arg in vars: 
    if ans is None: 
     ans = arg 
     continue 
    if key is not None: 
     if key(arg) < key(ans): 
      ans = arg 
    else: 
     if arg < ans: 
      ans = arg 

さらに、先にsorted()を使用してこれを行う方法はありますか。ここで

答えて

0

は何が起こっているのかを説明いくつかのコメントです:

# vars represents the items we're attempting to find the minimum of. 
# arg is the current item we're considering 
for arg in vars: 
    # ans is our running minimum value, and it initialized to None. If 
    # it's still None, this is the first arg we've tried, so just update 
    # the running minimum and move on to the next 
    if ans is None: 
     ans = arg 
     continue 
    # If a key function was passed, compare the result of passing our 
    # running minimum (ans) through it to the result of passing the 
    # current arg through it 
    if key is not None: 
     # If the result of the arg is less, make arg our new running 
     # minimum 
     if key(arg) < key(ans): 
      ans = arg 
    # If there was no key function supplied, just compare the values of 
    # the running minimum (ans) and the current arg 
    else: 
     # If the current arg is smaller, make it the new running minimum 
     if arg < ans: 
      ans = arg 

あなたはsortedを使用してもらえますか?もちろん、keyがあればそれを渡し、ソートされたリストの最初の項目を返すだけです。しかし、それはひどく効率的ではありません。リスト全体をソートするのは、最小値を見つけるために1回のパススルーをとるよりも遅くなります。