【问题标题】:Finding an element of an array that maximises the key function with recursion in python在python中使用递归查找最大化关键函数的数组元素
【发布时间】:2015-03-09 11:42:40
【问题描述】:

所以我需要在数组中找到输入键时会给出最大值的元素。此外,如果有多个元素这样做,则必须返回第一个元素。此外,关键参数必须是可选的;如果未提供,该函数必须返回第一个最大的元素。到目前为止,我想出了

def recursive_max(seq, key = lambda x: x):
    if len(seq) == 1:
        return seq[0]
    else:
        m = recursive_max(max(seq, key), key) .......

我很困惑。我不完全理解递归,但这里是我认为我需要采取的步骤。

1) Get element from the list
2) Input the key into the function
3) Initialize the max
4) Compare across the sequence (which is my array)

我很困惑如何用代码编写。

【问题讨论】:

标签: python arrays recursion lambda max


【解决方案1】:

如果需要递归,你可以去

def recursive_max(seq, key=lambda x: x):
    if len(seq) == 1:
        return seq[0]
    else:
        return max(seq[0], recursive_max(seq[1:], key), key=key)

在这里,您将数组的第一个元素与数组其余部分的最大值进行比较。

请注意,上面的版本不是尾递归的(尽管在 Python 中无关紧要 --- 或者至少在 CPython 中)。尾递归版本看起来像

def recursive_max2(seq, key=lambda x: x):
    if len(seq) == 1:
        return seq[0]
    else:
        return _recursive_max(seq[0], seq[1:], key)

def _recursive_max(x, xs, key):
    if len(xs) == 0:
        return x
    else:
        return _recursive_max(max(x, xs[0], key=key), xs[1:], key)

【讨论】:

    猜你喜欢
    • 2016-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-05
    • 2015-11-19
    • 1970-01-01
    • 2012-12-25
    • 2017-03-27
    相关资源
    最近更新 更多