我不知道你说的“我必须使用上面详述的结构”是什么意思。你有
start
,你想要
end
,所以在某个时刻,结构发生了变化。你的意思是说你根本不允许使用字典或列表吗?你的教练希望你从哪里开始
开始
到
终止
不使用其他任何东西?这里有一种方法,它只使用元组(和
开始
和
终止
列表)。
终止
将是元组的列表。我们将在单独的列表中跟踪坡度。预料
终止
和
lookup
看起来是这样的:
lookup = [ slope_1, , slope_2, ...]
end = [((p1_x, p1_y), (p2_x, p2_y), ...), ((p10_x, p10_y), (p11_x, p11_y)), ...]
start = [(((1, 2), 3), (2, 5)), (((4, 5), 2), (3, 7)), (((2, 4), 1), (8, 9)), (((1, 2), 3), (4, 8))]
end = []
lookup = []
def find_tuple_index_with_slope(needle_slope):
for index, item in enumerate(lookup):
if item == needle_slope:
return index
return None
for item in start:
p1 = item[0][0]
slope = item[0][1]
p2 = item[1]
# Check if end already contains this slope
slope_index = find_tuple_index_with_slope(slope)
if slope_index is None:
# If it doesn't exist, add an item to end
end.append(p1, p2))
# And add the slope to lookup
lookup.append(slope)
else:
# If it exists, append the new points to the existing value and
# reassign it to the correct index of end
end[slope_index] = (*end[slope_index], p1, p2)
现在,我们有
终止
看起来是这样的:
[((1, 2), (2, 5), (1, 2), (4, 8)), ((4, 5), (3, 7)), ((2, 4), (8, 9))]
这种方法不太好的原因是功能
find_tuple_index_with_slope()
需要迭代中的所有元素
终止
查找要附加到的正确值。这增加了代码的时间复杂性,当你可以使用字典进行查找时,速度会快得多,尤其是如果你有很多点和很多不同的斜率值。
一个更好的方法是:用一个新的字典替换查找函数,其中键是斜率的值,值是中的索引
终止
其中存储对应的元组。
lookup = dict()
end = []
for item in start:
p1 = item[0][0]
slope = item[0][1]
p2 = item[1]
# Find the index of the tuple for `slope` using the lookup
slope_index = lookup.get(slope, None)
if slope_index is None:
# If it doesn't exist, add an item to end
end.append((p1, p2))
# And add that index to lookup
lookup[slope] = len(end) - 1
else:
end[slope_index] = (*end[slope_index], p1, p2)
代码看起来
几乎
和以前一样,但使用字典而不是列表查找可以节省时间。