【发布时间】:2015-04-03 13:29:55
【问题描述】:
我最近一直在尝试学习递归算法,但我遇到了死胡同。给定一定数量的列表,每个列表代表从一个商店到所有其他商店所需的时间,以及一个包含一系列时间间隔的列表,有没有办法使用递归找到商店之间所有可能的路线?
例如
list_of_shops = [shop1, shop2, shop3, shop4]
# Index for this list and the one below are the same
list_of_time_it_takes = [[0, 2, 1, 4], [2, 0, 1, 4], [2, 1, 0, 4], [1, 2, 3, 0]]
# the 0 indicates the index of the shop. It takes 0 minutes to reach the shop from itself.
list_of_time_intervals = [0, 2, 2]
商店只能访问一次。我们可以看到以 2 分钟的间隔访问了 3 家商店,可能的路线是:
shop4 > shop2 > shop1
商店 3 > 商店 1 > 商店 2
所以我正在尝试使用以下代码通过所需的输出解决上述问题:
shops = [[0, 2, 1, 4, 9], [2, 0, 1, 4, 9], [2, 1, 0, 4, 9], [1, 2, 3, 0, 11], [3, 6, 16, 4, 0]]
times = [0, 2, 2, 4, 11]
list_of_shops = ['shop0', 'shop1', 'shop2', 'shop3', 'shop4']
index_dict = {}
def function(shops_input, times_input, i, index_list):
#print("given i = ", i)
#print("given shops = ", shops_input)
#print("given times = ", times_input)
shops_copy, times_copy = shops_input[:], times_input[:]
pop = times_copy.pop(0)
#print("obtained pop = ", pop)
if shops[i] in shops_copy:
index_list.append(shops.index(shops[i]))
shops_copy.pop(shops_copy.index(shops[i]))
if len(index_list) == len(times):
index_dict[list_of_shops[index_list[0]]] = index_list
print(index_list)
print(index_dict)
if len(times_copy):
try:
function(shops_copy, times_copy, shops[i].index(times_copy[0]), index_list)
except ValueError:
return
def main_function(shops, times):
for i in range(len(shops)):
function(shops, times, i, [])
print("---------end funct---------")
main_function(shops, times)
它在某些情况下有效,但绝对不是在所有情况下。它应该根据给定的时间间隔为我提供所有可能的路线,但是,它似乎在很多情况下都不起作用。
例如,如果我将商店和时间更改为:
shops = [[0,1,1,1],[1,0,1,1],[1,1,0,1],[1,1,1,0]]
times = [0, 1, 1]
它给出 2 种可能性的输出 -> 从 shop2 = [2,0,1] 和 -> 从 shop3 = [3,0,1] 开始。有什么方法可以让我的算法发挥作用吗?
【问题讨论】:
标签: python algorithm recursion