gpt4 book ai didi

python - 解构 if/else Python

转载 作者:行者123 更新时间:2023-12-01 09:24:03 29 4
gpt4 key购买 nike

我有一个程序,可以输出这样的一些条件(这是实际输出,它是伪代码):

if ( first occurance of 'AB' <= -0.5 ) {
return [ 0.]
} else {
if ( number of products viewed <= 1.5 ) {
if ( similarity to 'AB' <= 0.899999976158 ) {
return [ 1.]
} else {
return [ 0.]
}
} else {
if ( average time between actions <= 57.2111129761 ) {
return [ 0.39145907]
} else {
return [ 0.10410805]
}
}
}

如何获得更具人类可读性(?)/解构的解决方案?即:

( first occurance of 'AB' > -0.5 ) * (( number of products viewed <= 1.5 ) * ( similarity to 'AB' <= 0.899999976158 ))+((( number of products viewed > 1.5 ) * ( average time between actions <= 57.2111129761 ))

(我已经有了可以将“<=”更改为“>”的代码,但除此之外,我似乎无法以正确的顺序隔离每个 if 条件。

编辑:用于获取当前输出的代码(恐怕不是最小的例子)

def get_code(tree, feature_names, tabdepth=0):
left = tree.tree_.children_left
right = tree.tree_.children_right
threshold = tree.tree_.threshold
features = [feature_names[i] for i in tree.tree_.feature]
value = tree.tree_.value
f=[]

def recurse(left, right, threshold, features, node, f, tabdepth=0):
if (threshold[node] != -2):
print('\t' * tabdepth + 'if ( ' + features[node] + ' <= ' + str(threshold[node]) + ' ) {')
f.append('%' * tabdepth+'if ( ' + features[node] + ' <= ' + str(threshold[node]) + ' ) {')
if left[node] != -1:
recurse (left, right, threshold, features,left[node], f, tabdepth+1)
print('\t' * tabdepth+'} else {')
f.append('%' * tabdepth+'} else {')
if right[node] != -1:
recurse (left, right, threshold, features,right[node], f, tabdepth+1)
print('\t' * tabdepth + '}')
else:
print('\t' * tabdepth + 'return ' + str(value[node][0]))
f.append('%' * tabdepth + 'return ' + str(value[node][0]))

recurse(left, right, threshold, features, 0, f)

最佳答案

听起来您需要编写代码:

  1. 解析 if/else 伪代码的任何实例,构建树结构;那么
  2. 递归遍历树结构,生成所需的 bool 公式。

对于转换,主要思想是:

convert( if C then T else E )
==>
C * convert(T) + !C * convert(E)

如果您需要更具体的帮助,您可能应该提出更具体的问题。

关于python - 解构 if/else Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50586329/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com