【发布时间】:2019-06-12 04:48:02
【问题描述】:
我有一个循环增长算法(带有闭合链接的线增长),其中在每次迭代时在现有点之间添加新点。
每个点的链接信息作为一个元组存储在一个列表中。该列表会迭代更新。
问题:
将这些点的空间顺序作为列表返回的最有效方法是什么?
我是否需要在每次迭代时计算整个顺序,或者有没有办法以有序的方式将新点累积地插入到该列表中?
我能想到的只有以下几点:
tuples = [(1, 4), (2, 5), (3, 6), (1, 6), (0, 7), (3, 7), (0, 8), (2, 8), (5, 9), (4, 9)]
starting_tuple = [e for e in tuples if e[0] == 0 or e[1] == 0][0]
## note: 'starting_tuple' could be either (0, 7) or (0, 8), starting direction doesn't matter
order = list(starting_tuple) if starting_tuple[0] == 0 else [starting_tuple[1], starting_tuple[0]]
## order will always start from point 0
idx = tuples.index(starting_tuple)
## index of the starting tuple
def findNext():
global idx
for i, e in enumerate(tuples):
if order[-1] in e and i != idx:
ind = e.index(order[-1])
c = 0 if ind == 1 else 1
order.append(e[c])
idx = tuples.index(e)
for i in range(len(tuples)/2):
findNext()
print order
它正在工作,但它既不优雅(非 Pythonic)也不高效。 在我看来,递归算法可能更合适,但不幸的是我不知道如何实现这样的解决方案。
另外,请注意我使用的是 Python 2,并且只能访问完整的 Python 包(没有 numpy)
【问题讨论】:
-
如果您的代码运行正常并且您正在寻求改进,我建议您查看Code Review,他们会专注于突出改进领域。
-
@Jaba 感谢您的建议。
-
同样在你的第三行代码中,你可以用
order = list(starting_tuple)替换order = [starting_tuple[0], starting_tuple[1]] -
如果起始元组是
(7, 0)或(8, 0)之一怎么办——这可能吗?它不会破坏你最初的假设吗? -
@cdlane 两个元组都是有效的起始方向。脚本应该可以正常工作。
标签: python sorting recursion python-2.x