代码之家  ›  专栏  ›  技术社区  ›  which_command

python中的指数退避实现

  •  1
  • which_command  · 技术社区  · 7 年前

    我有两个列表“开始”和“结束”。长度相同(每个400万):

    for i in xrange(0,len(start)):
          print start[i], end[i]
    
    3000027 3000162
    3000162 3000186
    3000186 3000187
    3000187 3005000
    3005000 3005020
    3005020 3005090
    3007000 3007186
    3007186 3009000
    3009000 3009500
    .......
    

    enter image description here

    注:省略了旧内容

    最终,我要寻找的输出是(以上图为例):

    print density
      [4, 2, 1 ...........]
    

    虽然之前对这个问题的回答确实有效:

    density=[]
    i_s = 0
    while i_s < len(start):
         i_e = i_s
         while i_e < len(end):
             if end[i_e] - start[i_s] > 1000:
                 density.append(i_e - i_s + 1)
                 i_s = i_e
                 break
             i_e += 1
         i_s += 1
    
    
    print sum(density)/float(len(density))
    print max(density)
    print min(density)
    

    策略说明

    enter image description here

    counter=1 ##### initialise counter with value of 1
    def exponentially_increase_decrease(start, end, counter):
        distance=end-start
        if distance<=500:  ###500 is half the desired distance
            counter=exponentially_increase_decrease(start, end, counter*2)
        else:
            counter=-exponentially_increase_decrease(start, end, counter/2)
        print counter
        return counter
    

    在原始代码中调用函数:

    density=[]
    i_s = 0
    while i_s < len(start):
         i_e = i_s
         while i_e < len(end):
             if end[i_e] - start[i_s] > 1000:
                 density.append(i_e - i_s + 1)
                 i_s = i_e
                 break
             counter=counter=exponentially_increase_decrease(i_s, i_e, counter)
             i_e += counter
         i_s += 1
    

    (印刷数千次)

    counter=exponentially_increase_decrease(start, end, counter*2)
    RuntimeError: maximum recursion depth exceeded
    

    我对这种问题没有经验,也不确定我是否正确处理了它。。。有人能帮忙吗?

    2 回复  |  直到 7 年前
        1
  •  2
  •   juanpa.arrivillaga    7 年前

    这是我发现的少数几个案例之一 while i_e i_s 相互依赖。你可以用两个 range

    >>> start
    [3000027, 3000162, 3000186, 3000187, 3005000, 3005020, 3007000, 3007186, 3009000]
    >>> end
    [3000162, 3000186, 3000187, 3005000, 3005020, 3005090, 3007186, 3009000, 3009500]
    >>> i_s = 0
    >>> while i_s < len(start):
    ...     i_e = i_s
    ...     while i_e < len(end):
    ...         if end[i_e] - start[i_s] > 1000:
    ...             print(i_e - i_s + 1)
    ...             i_s = i_e
    ...             break
    ...         i_e += 1
    ...     i_s += 1
    ...
    4
    3
    1
    
        2
  •  0
  •   javidcf    7 年前

    不确定我是否理解正确。。。这就是你要找的吗?

    MAX_DIFF = 1000
    density = [0] * len(start)
    for i in range(len(start)):
        for j in range(i, len(end)):
            density[i] += 1
            if end[i] - start[i] >= MAX_DIFF:
                break
    print(density)