以下是示例数据结构:
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 :(得分: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 '))