在给定序列中求最大增量

2024-04-18 20:27:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前正在研究一个函数,它接受一个序列,并以较高的索引返回从一个元素到另一个元素的最大增量。但是,函数没有返回正确的最大增量。你知道吗

我将for循环放在for循环中,然后尝试从所有差异中返回最大值,但没有成功(它说'int' object is not iterable

def max_increase(seq):
    i = 0
    maximum_increase = 0
    for i in range(len(seq)):
        difference = 0
        for j in range(i + 1, len(seq)):
            difference = seq[j] - seq[i]
        if 0 <= maximum_increase < difference:
           maximum_increase = difference
    return maximum_increase

对于max_increase([1,2,3,5,0]),它应该返回4,因为从差异列表[1,2,4,-1,1,3,-2,2,-3,-5],最大值是4。但是,我的函数返回一个负值-1。你知道吗


Tags: 函数in元素forlenrange序列差异
3条回答

您可以使用:

my_l = [1,2,3,5,0]

max((e for i in range(len(my_l)) for e in (j - my_l[i] for j in my_l[i + 1:])))

输出:

4

如果您已经收到调试代码的帮助,下面是一个简短的pythonic解决方案:

>>> l=[1,2,3,5,0]
>>> inc = (i-el for p, el in enumerate(l) for i in l[p:])
>>> max(inc)
4

但更好的方法是避免创建不必要的切片(以颠倒顺序为代价):

import itertools as it


def incs(seq):
    pr = []
    for el in reversed(seq):
        print(f"{el} is compared with {pr}")
        yield (i-el for i in pr)
        pr.append(el)

seq = [1, 2, 3, 5, 0]
print("The max inc is", max(it.chain.from_iterable(incs(seq))))

产生

0 is compared with []
5 is compared with [0]
3 is compared with [0, 5]
2 is compared with [0, 5, 3]
1 is compared with [0, 5, 3, 2]
The max inc is 4

注:如果增加的是两个数字之间的距离,即无论符号如何,始终为正,则进行更改

yield (abs(i-el) for i in pr)

你有缩进问题。这解决了它:

def max_increase(seq):
    i = 0
    maximum_increase = 0
    for i in range(len(seq)):
        difference = 0
        for j in range(i + 1, len(seq)):
            difference = seq[j] - seq[i]
            if 0 <= maximum_increase < difference:
                maximum_increase = difference
    return maximum_increase

相关问题 更多 >