【发布时间】:2017-04-08 23:48:08
【问题描述】:
给定两个数组:
import numpy as np
L1 = np.array([3, 1, 4, 2, 3, 1])
L2 = np.array([4, 8, 9, 5, 6, 7])
我想有效地找到存在的最长连续间隙。
例如,让i 成为两个数组的第 i 个索引。
i = 0: elements = (3,4) -> gap in range 3-4 -> longest path = 1
i = 1: elements = (1,8) -> 3-4 intersect 1-8 is 3-4 -> longest path = 2
i = 2: elements = (4, 9) -> 3-4 intersect 4-9 is NULL -> longest path = 2
##this is what slows my approach down
#now, we must return to i = 1
i = 1: elements = (1,8) -> candidate interval is 1-8 -> path = 1, longest path = 2
i = 2: elements = (4,9) -> 1-8 intersect 4-9 is 4-8 -> path = 2, longest path = 2
i = 3: element = (2,5) -> 4-8 intersect 2-5 is 4-5 -> path = 3, longest path = 3
...
如果你试着想象它,它有点像flappy bird 游戏,所以我想找到的是这只鸟可以保持在同一水平而不死亡的最长时间
我想要一种不回溯的方法,以便我只遍历每个i 一次。有什么建议么?最好在python中
更新
我写了一些代码来可视化问题(注意我在这里假设最大行数是 10,但情况并非总是如此:
def get_flappy_matrix(ceiling, floor):
'''
given ceiling and floor heights
returns matrix of 1s and 0s
representing the tunnel
'''
ceil_heights = np.array(ceiling)
floor_heights = np.array(floor)
nmb_cols = len(ceil_heights)
flappy_m = np.ones(shape=(10, nmb_cols), dtype=np.int)
for col in range(nmb_cols):
for row in range(ceil_heights[col], floor_heights[col]):
flappy_m[row, col] = 0
return flappy_m
N = 6
L1 = np.array([3, 1, 4, 2, 3, 1])
L2 = np.array([4, 8, 9, 5, 6, 7])
m = get_flappy_matrix(L1, L2)
plt.pcolor(m, cmap=plt.cm.OrRd)
plt.yticks(np.arange(0, 10, 1), range(0, 11))
plt.xticks(np.arange(0, N+1),range(0,N+1))
plt.title(str(max_zero_len))
plt.gca().invert_yaxis()
plt.gca().set_aspect('equal')
plt.show()
现在,来自另一个 answer,这是解决问题的一种方法(对于大量输入仍然很慢):
max_zero_len = max(sum(1 for z in g if z == 0) for l in m for k, g in itertools.groupby(l))
print(max_zero_len)
# 5
【问题讨论】:
-
你将不得不解释更多。 “直线间隙”或“连续间隙”是什么意思?例如,您是否试图找到可以水平射击的最多墙壁,两个阵列代表一系列墙壁中孔的上下边缘?或者你正在做一些完全不同的事情?你让我们在这里猜了很多。
-
啊,很好,你给了我们更多的细节。
-
@user2357112 是的对不起,我知道它类似于游戏,但我不记得名字了哈哈
-
对不起,我没有得到你的问题。你能解释更多,或者你能用你的两个数组给出你最终想要的输出吗?这会很有帮助。
-
@ChihebNexus 最后的编辑有帮助吗?
标签: python arrays performance numpy