python - equation builder using loops -
i'm trying write program iterates through possible simple equations find value of 24. managed loop done there i'm not catching.
the idea theres 3 level loop (i guess theta(n^3)?, im bad time complexity), used build equation 4 numbers (randomly generated in program) added list.
numlist = [x2, x3, x4]
here code have:
for in range(4): j in range(4): k in range(4): l in range(len(numlist)): n += 1 print(i, j, k, " i, j, k") print(x2, x3, x4, "x2, x3, x4") print(x, "x supposed reset") print(l, "val of l") print(n, "val of n") if == 0 or j == 0 or k == 0: x += "+" x += str(numlist[n]) print(x, "add") if == 1 or j == 1 or k == 1: x += "-" x += str(numlist[n]) print(x, "sub") if == 2 or j == 2 or k == 2: x += "*" x += str(numlist[n]) print(x, "mult") if == 3 or j == 3 or k == 3: x += "/" x += str(numlist[n]) print(x, "div") if n == 2: print() print("----") print(x, "final") print(eval(x), "evald") if eval(x) not 24: x = x1 print(x, "x reset") else: print(eval(x), "= 24") n = -1 print("----")
the error comes in when, reason, string i'm building , evaluating (x) not reset, , instead adds same string generated in last loop iteration (it's supposed default value). default value of x randomly generated:
x = str(randrange(1, 9))
it's weird me, i'm not sure going wrong, loop acting switch conditional statement without breaks. here console output: pasted pastebin
can tell me doing wrong? or going on in code not seeing why x not being reset if new string being built (this want)?
edit: here entire source: equation.py
the problem isn't 'x isn't being reset'. problem code not designed use 3 operators on each pass through. example, if 0, j 1 , k 2 use + due being 0, - due j being 1 , * due k being 2, every single number in equation, you'd see things 1+5-5*5+6-6*6+4-4*4
of operators repeated 3 times.
you want logic more this, explicitly use 3 operators , iterate on combinations of 3 operators:
from random import randrange def brute_force(): x1 = randrange(1, 9) x2 = randrange(1, 9) x3 = randrange(1, 9) x4 = randrange(1, 9) numlist = [x1, x2, x3, x4] operatorlist = ["+", "-", "/", "*"] equation = "" in range(4): j in range(4): k in range(4): equation = str(numlist[0]) + operatorlist[i] + str(numlist[1]) + operatorlist[j] + str(numlist[2]) + operatorlist[k] + str(numlist[3]) print("equation: " + equation) print("evaluation: " + str(eval(equation))) if __name__ == "__main__": brute_force()
output looks like
>>> brute_force() equation: 4+6+4+6 evaluation: 20 equation: 4+6+4-6 evaluation: 8 equation: 4+6+4/6 evaluation: 10 equation: 4+6+4*6 evaluation: 34 equation: 4+6-4+6 evaluation: 12 equation: 4+6-4-6 evaluation: 0 equation: 4+6-4/6 evaluation: 10 ...
Comments
Post a Comment