【问题标题】:Recursive function to build a string from dictionaries从字典构建字符串的递归函数
【发布时间】: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


【解决方案1】:

您可以将递归与生成器一起使用:

hints = ['one','two','three', 'four']
d = {'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'}}}
def get_vals(s, c = [], t=[]):
   if (k:=next(filter(lambda x:x not in t, hints), None)):
      for a, [b] in d.get(f'{s}{k}', {}).items():
         yield from get_vals(a, c=c+[b], t=t+[k])
   else:
      yield c+[s]

print(list(get_vals('ROME')))
        

输出:

[['hello', 'how', 'are', 'you', 'MILAN'], 
 ['hello', 'im', 'john', 'smith', 'FLORENCE'], 
 ['money', 'in', 'the', 'bank', 'CANCUN'], 
 ['racing', 'cars', 'are', 'fast', 'LONDON']]

【讨论】:

  • 非常感谢您的帮助!
猜你喜欢
  • 2019-06-03
  • 2017-10-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-05
  • 2017-07-07
  • 2021-12-28
相关资源
最近更新 更多