2017-06-01 78 views
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 ')) 
+0

你真的應該考慮你的數據結構在這裏。特別是,爲什麼要使用'list'?爲什麼不是一個純粹的'字典'字典?有一個列表會使你創建和修改你的'commands'樹的邏輯複雜化,更不用說它會使你想要完成的任務複雜化。 –

+0

我看了一下使用Tries,但我找不到任何使用複雜結構的例子(大多數只是從簡單的單詞列表中自動完成)。 –

+0

您可以根據單詞中的字符使用樹狀結構,但可以很容易地將其擴展爲句子中的標記......但不管怎樣,您仍然應該考慮您在此處具有的樹。這不是一個合適的樹,真的,它是一個列表/其他詞典的字典。實質上,您的「節點」不是封裝類型,實際上根據節點的性質而不同。這使你的邏輯複雜化。爲什麼不放棄列表並只使用嵌套'dict's? –

回答

0

以下Jaunpa的建議更改數據結構要明確字典後,我才得以大大壓縮邏輯,並得到所有實例的工作:

def get_choices(commands, search): 
    parts = search.split(' ') 
    for part in parts: 
     if part in commands: 
      if len(parts) > 1: 
       return get_choices(commands[part], ' '.join(parts[1:])) 
      else: 
       return [] 
     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 '))