【问题标题】:Itertools.accumulate to find union of intervals (convert from reduce to accumulate)Itertools.accumulate 查找区间的并集(从减少转换为累积)
【发布时间】:2019-01-31 00:34:05
【问题描述】:

我似乎开发了正确的reduce 操作来找到区间的并集,却发现reduce 为您提供了最终结果。所以我查阅了文档,发现我应该使用的其实是accumulate

我需要有人帮我把这个reduce 转换成accumulate 所以我有中间间隔

下面的代码是我如何使用reduce 的示例。我假设可以使用accumulate 存储中间值。我不确定这是否可能。但我查看了accumulate 为您提供项目列表的示例,其中每个项目都是中间计算结果。

example_interval = [[1,3],[2,6],[6,10],[15,18]]

def main():

    def function(item1, item2):


        if item1[1] >= item2[0]:

            return item1[0], max(item1[1], item2[1])

        else:

            return item2

    return reduce(function, example_interval)

为了理解这个问题,[1, 3], [2, 6]可以简化为[1, 6],因为item1[1] >= item2[0],然后[1, 6]被取为item1,然后与[6,10]比较,即item2,得到@ 987654337@。然后将[1, 10]与最终项[15, 18]进行比较,在这种情况下,它没有合并,所以最终结果是[1, 10], [15, 18]

我知道如何在没有reduceaccumulate 的情况下解决这个问题。 我只是对了解如何使用 accumulate 来复制存储中间值的任务感兴趣。

【问题讨论】:

    标签: python intervals itertools functools accumulate


    【解决方案1】:
    from itertools import accumulate
    
    def function(item1, item2):
        if item1[1] >= item2[0]:
            return item1[0], max(item1[1], item2[1])
        return item2
    
    example_interval = [(1,3),(2,6),(6,10),(15,18)]
    print(list(accumulate(example_interval, function)))
    

    结果是:

    [(1, 3), (1, 6), (1, 10), (15, 18)]
    

    请注意,我将 example_interval 上的项目从列表更改为元组。 如果你不这样做,当item1[1] < item2[0]时,返回值为item2 这是一个列表对象,但如果是item[1] >= item2[0],则返回的表达式是item1[0], max(item1[1], item2[1]),转化为一个元组:

    example_interval = [[1,3],[2,6],[6,10],[15,18]]
    print(list(accumulate(example_interval, function)))
    

    现在的输出是:

    [[1, 3], (1, 6), (1, 10), [15, 18]]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-05-02
      • 2021-08-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-19
      • 2023-03-15
      相关资源
      最近更新 更多