我有以下格式的启发式:
if a == 1 and b == 1 and c == 1:
do something
if a == 1 and b == 1 and c == 2:
do something
if a == 3 and b == 2 and c == 1:
do something
if a == 2 and b == 2 and c == 1:
do something
if a == 3 and b == 1 and c == 3:
do something
etc.
当然,这会进行许多不必要的比较,如果这些语句是这样嵌套的话可以避免:
if a == 1:
if b == 1:
if c == 1:
do something
if c == 2:
do something
etc.
假设我有一个案例的元组集(a, b, c)
是有限的,并且每个元组具有被算法接收的相同可能性,我怎样才能生成最优的决策树,即它对一般情况进行最少的比较,或者在所有输入都通过它时最小化比较总数?
我想象这样的事情:
In: optimal_tree([(1, 1, 1), (1, 1, 2)])
Out: "if a == 1:
if b == 1:
if c == 1:
do something
if c == 2:
do something"
In: optimal_tree([(1, 1), (2, 1), (2, 2)])
Out: "if a == 2:
if b == 1:
do something
if b == 2:
do something
if a == 1:
do something"
OR
"if b == 1:
if a == 1:
do something
if a == 2:
do something
if b == 2:
do something"
答案 0 :(得分:1)
规则引擎和数据库查询也经常处理这个问题。您可能希望了解这些背后的实现。
他们有几种方法来解决这个问题(虽然没有一个是完美的):
如果你想让你的算法更快,你可能想要研究哈希和&索引,如果你还没有这样做。这带来了更大的规模优势。