替换python中内置的min函数

发布于 2024-09-28 12:41:47 字数 243 浏览 3 评论 0原文

我应该编写一个函数 min_in_list(munbers),它需要一个列表 数字并返回最小的一个。注意:不允许使用内置函数 min

def min_in_list(numbers):
    the_smallest = [n for n in numbers if n < n+1]
    return the_smallest

怎么了?

I should write a function min_in_list(munbers), which takes a list of
numbers and returns the smallest one. NOTE: built-in function min is NOT allowed!

def min_in_list(numbers):
    the_smallest = [n for n in numbers if n < n+1]
    return the_smallest

What's wrong?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

巴黎盛开的樱花 2024-10-05 12:41:47
def min_of_two(x, y):
    if x >= y: return x
    else: return y

def min_in_list(numbers):
    return reduce(min_of_two, numbers)

您必须从列表中生成 1 个数字,而不仅仅是另一个列表。这就是 reduce 函数的工作(当然,你可以不使用 reduce 来实现它,但以此类推)。

def min_of_two(x, y):
    if x >= y: return x
    else: return y

def min_in_list(numbers):
    return reduce(min_of_two, numbers)

You have to produce 1 number from list, not just another list. And this is work for reduce function (of course, you can implement it without reduce, but by analogy with it).

缺⑴份安定 2024-10-05 12:41:47

干得好。这几乎肯定是您能做到的最简单的事情。当你交作业时,你甚至不必给我学分。

import itertools
import functools
import operator

def min(seq, keyfun=operator.gt):
    lt = lambda n: functools.partial(keyfun, n)

    for i in seq:
        lti = lt(i)
        try:
            next(itertools.ifilter(lti, seq))
        except:
            return i

Here you go. This is almost certainly about as simple as you could make it. You don't even have to give me credit when you turn the assignment in.

import itertools
import functools
import operator

def min(seq, keyfun=operator.gt):
    lt = lambda n: functools.partial(keyfun, n)

    for i in seq:
        lti = lt(i)
        try:
            next(itertools.ifilter(lti, seq))
        except:
            return i
夜无邪 2024-10-05 12:41:47
min = lambda n: return reduce(lambda x,y: (x>y) and return x or return y,n)

从未经过测试,使用风险自负。

min = lambda n: return reduce(lambda x,y: (x>y) and return x or return y,n)

Never been tested, use at your own risk.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文