【发布时间】:2021-03-24 12:43:06
【问题描述】:
我遇到了递归函数的问题。
hints = ['one','two','three', 'four']
firstCity = 'ROME'
dictionary = { 'ROMEone' : { 'PARIS' : {'hello'} , 'CAIRO': {'money'}, 'MOSCOW': {'racing'} },
'CAIROtwo': { 'MILAN' : {'in'}},
'PARIStwo': { 'BERLIN' : {'how'} , 'CANCUN' : {'im'} },
'MOSCOWtwo': { 'AMSTERDAM' : {'cars'} },
'BERLINthree': { 'AMSTERDAM' : {'are'} },
'AMSTERDAMthree' : { 'MILAN' : {'are'} },
'MILANthree' : { 'PARIS' : {'the'} },
'CANCUNthree' : { 'LONDON' : {'john'}},
'AMSTERDAMfour': { 'MILAN' : {'you'} },
'MILANfour': { 'LONDON' : {'fast'} },
'PARISfour': { 'CANCUN' : {'bank'} },
'LONDONfour': { 'FLORENCE' : {'smith'}} }
该函数的目的是从“firstCity”开始在字典中搜索,找出所有可以从字典中提取的可能短语。
对于字典的每个元素,都有 2 个信息:目的地(在哪里查看)和单词(构建我们正在寻找的短语)
结果应该是:
[ ["hello how are you" , "MILAN"],
["hello im john smith", 'FLORENCE"],
["money in the bank", "CANCUN"],
["racing cars are fast", "LONDON"] ]
到目前为止,我想出了这个解决方案,但它不能正常工作,我可以请教一些如何解决这个问题的建议吗?请!
def ex(dictionary, hints, firstCity, words = []):
for key in dictionary:
if key == (firstCity + hints[0]):
for destination in dictionary[key]:
firstCity = destination
word = getValue(dictionary[key][destination])
#getValue simply get the value from the set
words.append(word)
if hints[1:] == []:
return words
ex(dictionary, hints[1:], firstCity,words)
return words
def getValue(st):
for el in st:
if len(st) == 1:
return el
具有值的函数的结果将是:
['hello','how','are','you','are','fast','the','bank','im','john','smith','money','in','the','bank','racing','cars','are','fast','the','bank']
【问题讨论】:
-
请用您正在使用的实际输入和您看到的实际输出更新您的问题。
-
那些顶级键是什么?
ROMEone实际上是字符串"ROMEone"还是绑定到某个其他类型的某个对象的变量名?字典中不同层次的嵌套的语义是什么?对于您想要的,这似乎是一个非常尴尬的数据结构。 -
正如@quamrana 轻轻地说我需要更新问题,还不够清楚。
-
虽然我还是不明白你是怎么称呼的。你的意见是什么?
-
它的输入是 firstCity = 'ROME' 和提示列表 ['one','two','three', 'four'] 显然是字典
标签: python dictionary recursion binary-search-tree