Python中的指数回退实现

2024-04-23 19:48:34 发布

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

我有两个单子“开始”和“结束”。它们的长度相同(每个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
.......

我的问题是我想迭代两个列表,从同一点开始,但是沿着“结束列表”逐步迭代,直到找到一个值,其中“start[I]”和“end[I+x]”之间的差值大于1000。在

enter image description here

我已经做了最好的尝试,我使用一个无休止的循环来迭代“结束列表”,直到与start的差异超过1000,然后从该点开始并从那里执行相同的操作。。。在

注:旧内容省略

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

^{pr2}$

有人能帮我吗?在

更新

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

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)

我担心代码是极其缓慢的,因为我正在更新'I'u e'的扩展,每次在内部while循环的迭代中添加1。。。 为了解决这个问题,我想创建一个“counter”变量,它将动态地扩展“I\u e”变量。这将通过递归来实现,即iˉe变量将以指数方式增加,直到达到所需距离的一半,然后按指数减小,直到达到所需距离。在

策略说明

enter image description here

我的尝试如下:

我创建了一个递归的a函数来更新变量'counter'

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

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


Tags: 列表lenifcounterdensitystartenddistance
2条回答

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

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)

这是我发现while循环更直接的少数几种情况之一,因为i_e和{}相互依赖。您可以使用两个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

相关问题 更多 >