python - Returning concatenated string as global variable -
so here code using :
global output_res output_res = "" def recurse(left, right, threshold, features, node, depth): spacer = spacer_base * depth if (threshold[node] != -2): """print(spacer + "if ( " + features[node] + " <= " + \ str(threshold[node]) + " ) {")""" output_res += spacer + "if ( " + features[node] + " <= " + \ str(threshold[node]) + " ) {" if left[node] != -1: recurse (left, right, threshold, features, left[node], depth+1) """print(spacer + "}\n" + spacer +"else {")""" output_res += spacer + "}\n" + spacer +"else {" if right[node] != -1: recurse (left, right, threshold, features, right[node], depth+1) """print(spacer + "}")""" output_res += spacer + "}" else: target = value[node] i, v in zip(np.nonzero(target)[1], target[np.nonzero(target)]): target_name = target_names[i] target_count = int(v) """print(spacer + "return " + str(target_name) + " ( " + \ str(target_count) + " examples )")""" output_res += spacer + "return " + str(target_name) + " ( " + \ str(target_count) + " examples )" return output_res recurse(left, right, threshold, features, 0, 0)
as can see recurse()
recursive function, aim to retrieve output_res
, , use in main function, using code having error :
local variable 'output_res' referenced before assignment
update
i found exact solution looking :
temp_list = [] def recurse(temp_list, left, right, threshold, features, node, depth): spacer = spacer_base * depth if (threshold[node] != -2): temp_list.append(spacer + "if ( " + features[node] + " <= " + \ str(threshold[node]) + " ) {") if left[node] != -1: recurse (temp_list, left, right, threshold, features, left[node], depth+1) temp_list.append(spacer + "}\n" + spacer +"else {") if right[node] != -1: recurse (temp_list, left, right, threshold, features, right[node], depth+1) temp_list.append(spacer + "}") else: target = value[node] i, v in zip(np.nonzero(target)[1], target[np.nonzero(target)]): target_name = target_names[i] target_count = int(v) temp_list.append(spacer + "return " + str(target_name) + " ( " + \ str(target_count) + " examples )") recurse(temp_list, left, right, threshold, features, 0, 0) return '\n'.join(temp_list)
if want go global variable
output_res = "" def recurse(left, right, threshold, features, node, depth): global output_res //your code //no need "return output_res" recurse(left, right, threshold, features, 0, 0)
explanation:
in [8]: myg = 5 in [9]: def fun1(): ...: myg=45 ...: in [10]: def fun2(): ....: print myg in [11]: fun1() in [12]: fun2() 5 //output //now change fun1 global in [15]: def fun1(): ....: global myg ....: myg=45 in [17]: fun1() in [18]: fun2() 45 //output, explains how global affects scope
Comments
Post a Comment