Python exercises answer: as close to zero [difficulty: Level 1] - View the Python programming examples training camp 1000 title track machine waiting for you to challenge

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/aumtopsale/article/details/102752567

Closest to zero [difficulty: Level 1]:

Answer 1:

def closest(lst):
    m = min(lst, key=abs)
    return m if m == 0 or -m not in lst else None

Answer 2:

def closest(lst):
    result = min(lst, key=abs)
    return result if not result or -result not in lst else None

Answer 3:

def closest(lst):
    m = min(lst, key=lambda x: abs(x))
    if not m or -m not in lst: return m​

Answer 4:

def closest(lst):
    lst = sorted(set(lst), key=abs)
    if len(lst) > 1 and abs(lst[0]) == abs(lst[1]):
        return None
    return lst[0]

Answer 5:

def closest(lst):
    min_v = min(lst, key=lambda x: abs(x))
    return None if -min_v in lst and min_v else min_v​

A6:

from functools import reduce; closest=lambda arr: (lambda r: None if r[1] else r[0])(reduce(lambda a,b: [a[0],True] if a[0] and a[0]==-b else [b,False] if abs(b)<abs(a[0]) else a,arr,[999999,False]))

A7:

def closest(lst):
    if 0 in lst:
        return 0
    lst = sorted(lst, key=lambda i: abs(i))
    return lst[0] if lst[0] * (-1) not in lst else None

A8:

def closest(arr1):
    ranked = sorted(arr1, key = lambda x: abs(x))

    lowest = [num for num in arr1 if abs(num) == abs(ranked[0])]

    if len(set(lowest)) == 1:
        return lowest[0]
    else:
        return None

A9:

def closest(lst):
    lst = sorted(set(lst), key=abs)
    return lst[0] if len(lst) < 2 else None if abs(lst[0]) == abs(lst[1]) else lst[0]

Answers 10:

def closest(lst):
    l = sorted(set(lst), key=lambda x: abs(x))
    if len(l) == 1 or abs(l[0]) != abs(l[1]):
        return l[0]



Python basic training campView more Python base camp QQ group

Here Insert Picture Description
Welcome to the graduates plus group discussions, learn together, grow together!

Guess you like

Origin blog.csdn.net/aumtopsale/article/details/102752567