0
這裏的樹是樣本數據結構:提供自動完成功能與命令
commands = {
'accounts': {},
'exit': {},
'login': {},
'query': {'bank': {}, 'savings': {}},
'transactions': {'monthly': {}},
'update': {
'now': {'please': {}},
'tomorrow': {'please': {}}
}
}
如果我們假裝邏輯是get_choices我希望下面的輸出:
>> get_choices('upd')
['accounts', 'exit', 'login', 'query', 'transactions', 'update']
>> get_choices('update')
[]
>> get_choices('update ')
['now', 'tomorrow']
>> get_choices('update now ')
['please']
>> get_choices('update now please ')
[]
這是我的嘗試它,它適用於上述情況,除了第二個,在這種情況下,它返回['now', 'tomorrow']
。
def get_choices(commands, search):
parts = search.split(' ')
for part in parts:
if part in commands:
return get_choices(commands[part], ' '.join(parts[1:]))
else:
return list(commands.keys())
commands = {
'accounts': {},
'exit': {},
'login': {},
'query': {'bank': {}, 'savings': {}},
'transactions': {'monthly': {}},
'update': {
'now': {'please': {}},
'tomorrow': {'please': {}}
}
}
print(get_choices(commands, 'upd'))
print(get_choices(commands, 'update'))
print(get_choices(commands, 'update '))
print(get_choices(commands, 'update now '))
print(get_choices(commands, 'update now please '))
你真的應該考慮你的數據結構在這裏。特別是,爲什麼要使用'list'?爲什麼不是一個純粹的'字典'字典?有一個列表會使你創建和修改你的'commands'樹的邏輯複雜化,更不用說它會使你想要完成的任務複雜化。 –
我看了一下使用Tries,但我找不到任何使用複雜結構的例子(大多數只是從簡單的單詞列表中自動完成)。 –
您可以根據單詞中的字符使用樹狀結構,但可以很容易地將其擴展爲句子中的標記......但不管怎樣,您仍然應該考慮您在此處具有的樹。這不是一個合適的樹,真的,它是一個列表/其他詞典的字典。實質上,您的「節點」不是封裝類型,實際上根據節點的性質而不同。這使你的邏輯複雜化。爲什麼不放棄列表並只使用嵌套'dict's? –