Python 在字典中查找所有可能路径(x步)的递归函数
我有一本字典,其中包含如下所述的键和值: -每个键都是一个元组,其中第一个元素是颜色,第二个元素是数字,两者都是字符串 -每个值都是一个或多个元组的列表,每个元组的第一个元素是颜色名称,第二个元素是水果名称(同样,两者都是字符串) 例如:Python 在字典中查找所有可能路径(x步)的递归函数,python,dictionary,recursion,tuples,Python,Dictionary,Recursion,Tuples,我有一本字典,其中包含如下所述的键和值: -每个键都是一个元组,其中第一个元素是颜色,第二个元素是数字,两者都是字符串 -每个值都是一个或多个元组的列表,每个元组的第一个元素是颜色名称,第二个元素是水果名称(同样,两者都是字符串) 例如: given_dict = {('Red', 'one'): [('Blue', 'strawberry'), ('Yellow', 'banana')], ('Yellow', 'three'): [('Green', 'pe
given_dict = {('Red', 'one'): [('Blue', 'strawberry'), ('Yellow', 'banana')],
('Yellow', 'three'): [('Green', 'peach')],
('Green', 'seven'): [('Purple', 'lemon')],
('Blue', 'three'): [('Purple', 'pineapple')],
('Purple', 'three'): [('Red', 'strawberry')],
('Purple', 'seven'): [('White', 'banana'), ('Green', 'dragonfruit')],
('White', 'seven') : [('Green', 'melon')]}
然后我有一个数字列表(作为字符串),这些数字正是作为字典键中的第二个元素包含的数字。
例如:
我想做的是创建一个递归函数,而不导入库,将颜色(作为字符串)、字典和如上所述的数字列表作为输入,并查找所有可能的路径,这些路径从给定的输入颜色和列表w[0]开始,并以对应于(输入颜色,列表w)的值继续[iteration])直到列表[iteration]==len(列表[U/w]
由于我不善于解释(对此我深表歉意),我将举一个例子来说明我的意思:
输入:
第一条道路:
('Red', 'one') -> ('Blue', 'strawberry') #input_color = 'Red' | list_of_w[0] = 'one'
('Blue', 'three') -> ('Purple', 'pineapple') #input_color = 'Blue' | list_of_w[1] = 'three'
('Purple', 'seven') -> ('White', 'banana') #input_color = 'Purple' | list_of_w[2] = 'seven'
1st path returns ('strawberry pineapple banana', 'White')
第二条道路:
('Red', 'one') -> ('Blue', 'strawberry') #input_color = 'Red' | list_of_w[0] = 'one'
('Blue', 'three') -> ('Purple', 'pineapple') #input_color = 'Blue' | list_of_w[1] = 'three'
('Purple', 'seven') -> ('Green', 'dragonfruit') #input_color = 'Purple' | list_of_w[2] = 'seven'
2nd path returns ('strawberry pineapple dragonfruit', 'Green')
第三条道路:
('Red', 'one') -> ('Yellow', 'banana') #input_color = 'Red' | list_of_w[0] = 'one'
('Yellow', 'three') -> ('Green', 'peach') #input_color = 'Yellow' | list_of_w[1] = 'three'
('Green', 'seven') -> ('Purple', 'lemon') #input_color = 'Green' | list_of_w[2] = 'seven'
3rd path returns ('banana peach lemon', 'Purple')
最后,函数应返回所有可能路径的列表,作为元组(string_of_four,last_color),在这种情况下:
[('strawberry pineapple banana', 'White'), ('strawberry pineapple dragonfruit', 'Green'), (‘banana peach lemon', 'Purple')]
首先,我初始化了一些变量以帮助进行一些计算:
t = 0 #this will be increased by 1 each time: when (t == l) I may have found a path
l = len(list_of_w) #to know when I finished the steps
set_end = set() #to save values I've already found before
list_of_fruits, result = list(), list() #same as above
然后我编写了我函数的代码:
def r_find_path(given_dict, t, l, result, list_of_fruits, list_of_w, initial_color, set_end):
start = (initial_color, list_of_w[t])
if (start not in given_dict.keys()):
return ()
if (t == l): #arrived at the end
for end in given_dict[start]:
list_of_fruits.append(end[1])
final_color = end[0]
str_colors = ' '.join(list_of_fruits)
set_end.add(end)
result = [(str_colors, final_color)]
t = 0
list_of_fruits = list()
return result[0] + r_find_path(given_dict, t, l, result, list_of_fruits, list_of_w, initial_color, set_end)
else: #if(t < l):
for end in given_dict[start]:
if (end not in set_end):
list_of_fruits.append(end[1])
initial_color = end[0]
set_end.add(end)
return r_find_path(given_dict, t+1, l, result, list_of_fruits, list_of_w, initial_color, set_end)
我的功能的实际结果是:
('strawberry pineapple banana', 'White')
看来我的函数有两个问题:
1) 它不返回列表,而是返回元组
2) 它在第一条路径停止,而不是搜索其他两条路径
有人能帮我看看我做错了什么吗?看来我在正确理解和使用递归时遇到了很多麻烦
根据要求,这是我完整的真实代码:
def function(initial_color, string_of_w):
given_dict = {('Red', 'one'): [('Blue', 'strawberry'), ('Yellow', 'banana')],
('Yellow', 'three'): [('Green', 'peach')],
('Green', 'seven'): [('Purple', 'lemon')],
('Blue', 'three'): [('Purple', 'pineapple')],
('Purple', 'three'): [('Red', 'strawberry')],
('Purple', 'seven'): [('White', 'banana'), ('Green', 'dragonfruit')],
('White', 'seven') : [('Green', 'melon')]}
t = 0
list_of_w = string_of_w.split()
result, list_of_fruits = tuple(), list()
l = len(list_of_w) - 1
set_end = set()
return r_find_path(given_dict, t, l, result, list_of_fruits, list_of_w, initial_color, set_end)
def r_find_path(given_dict, t, l, result, list_of_fruits, list_of_w, initial_color, set_end):
start = (initial_color, list_of_w[t])
if (start not in given_dict.keys()):
return ()
if (t == l): #arrived at the end
for end in given_dict[start]:
list_of_fruits.append(end[1])
final_color = end[0]
str_colors = ' '.join(list_of_fruits)
set_end.add(end)
result = [(str_colors, final_color)]
t = 0
list_of_fruits = list()
return result[0] + r_find_path(given_dict, t, l, result, list_of_fruits, list_of_w, initial_color, set_end)
else: #if(t < l):
for end in given_dict[start]:
if (end not in set_end):
list_of_fruits.append(end[1])
initial_color = end[0]
set_end.add(end)
return r_find_path(given_dict, t+1, l, result, list_of_fruits, list_of_w, initial_color, set_end)
应返回:
('strawberry pineapple banana', 'White')
使用递归生成器构造简单 代码
def r_find_path(given_dict, list_of_w, initial_color, path=None):
' Recursive generator'
# Path holds the sequence of color, fruit
# tuples for a path
if path is None:
path = []
# Base case
# at end of path
# since list_of_w is empty
if not list_of_w:
# Created desired string from path elements
yield ' '.join(x[1] for x in path), path[-1][0]
else:
# key with this color and list_of_w value
start = (initial_color, list_of_w[0])
# Recursively list of values
for end in given_dict[start]:
yield from r_find_path(given_dict, list_of_w[1:], end[0], path + [end])
测试
given_dict = {
('Red', 'one'): [('Blue', 'strawberry'), ('Yellow', 'banana')],
('Yellow', 'three'): [('Green', 'peach')],
('Green', 'seven'): [('Purple', 'lemon')],
('Blue', 'three'): [('Purple', 'pineapple')],
('Purple', 'three'): [('Red', 'strawberry')],
('Purple', 'seven'): [('White', 'banana'), ('Green', 'dragonfruit')]}
list_of_w = ['one', 'three', 'seven']
input_color = 'Red'
# Get list of all solutions
result = list(r_find_path(given_dict, list_of_w, input_color))
# Display solution on each line
print(*result, sep = '\n')
('strawberry pineapple banana', 'White')
('strawberry pineapple dragonfruit', 'Green')
('banana peach lemon', 'Purple')
输出
given_dict = {
('Red', 'one'): [('Blue', 'strawberry'), ('Yellow', 'banana')],
('Yellow', 'three'): [('Green', 'peach')],
('Green', 'seven'): [('Purple', 'lemon')],
('Blue', 'three'): [('Purple', 'pineapple')],
('Purple', 'three'): [('Red', 'strawberry')],
('Purple', 'seven'): [('White', 'banana'), ('Green', 'dragonfruit')]}
list_of_w = ['one', 'three', 'seven']
input_color = 'Red'
# Get list of all solutions
result = list(r_find_path(given_dict, list_of_w, input_color))
# Display solution on each line
print(*result, sep = '\n')
('strawberry pineapple banana', 'White')
('strawberry pineapple dragonfruit', 'Green')
('banana peach lemon', 'Purple')
好的,这就是我想到的:
def搜索(给定目录、列表、输入颜色、当前字符串、返回):
w=列表w[0]
k=(输入颜色,w)
nxt=给定值[k]
如果len(列表w中的列表w)==1:
对于nxt中的k:
c、 f=k
最后一个字母=当前字母[:]+[f]
final_str=''.join(final_str)
附加注释((最后一个字符,c))
其他:
对于nxt中的k:
c、 f=k
nxt_str=当前str[:]+[f]
搜索(给定目录,列表w[1]、c、nxt、ret)
给定条件={
(‘红色’、‘一’):[(‘蓝色’、‘草莓’、(‘黄色’、‘香蕉’)],
(‘黄色’、‘三’):[(‘绿色’、‘桃色’)],
(‘绿色’、‘七’):[(‘紫色’、‘柠檬’)],
(‘蓝色’、‘三’):[(‘紫色’、‘菠萝’)],
(‘紫色’、‘三’):[(‘红色’、‘草莓’)],
(‘紫色’、‘七’):[(‘白色’、‘香蕉’、(‘绿色’、‘龙牙’)],
(‘白’、‘七’):[(‘绿’、‘瓜’)]
}
清单w=['1','3','7']
初始颜色=‘红色’
ret=[]
搜索(给定目录、列表、首字母颜色、[]和ret)
打印(ret)
按要求输出我猜你的
返回
缩进了一级太多。因为它们在for
循环中,它们会在第一次迭代时停止循环。即使我将它们移到左侧,结果也不会改变。不幸的是,请发布你的真实代码。当我将你的帖子粘贴到IDE中时,它会抱怨about无效引号:('Red','one')
etcI将引号从''更改为''。现在它应该可以正常工作了,很抱歉给您带来不便。逗号:('Red','one'):[('Blue','草莓'),('Yellow','banana')],
等…我可以问一下:>>如果没有列出的话:如果x:
通常可以翻译为如果bool(x)=True:
或者如果没有x:
如果bool(x)=False,那么如果没有列出的话:
意味着如果的列表
是空的。
given_dict = {
('Red', 'one'): [('Blue', 'strawberry'), ('Yellow', 'banana')],
('Yellow', 'three'): [('Green', 'peach')],
('Green', 'seven'): [('Purple', 'lemon')],
('Blue', 'three'): [('Purple', 'pineapple')],
('Purple', 'three'): [('Red', 'strawberry')],
('Purple', 'seven'): [('White', 'banana'), ('Green', 'dragonfruit')]}
list_of_w = ['one', 'three', 'seven']
input_color = 'Red'
# Get list of all solutions
result = list(r_find_path(given_dict, list_of_w, input_color))
# Display solution on each line
print(*result, sep = '\n')
('strawberry pineapple banana', 'White')
('strawberry pineapple dragonfruit', 'Green')
('banana peach lemon', 'Purple')