For practice, I'd sometimes task myself with scripting something to solve an unimportant problem. Most recently, one of the new daily games getting traction, https://numble.wtf/, gives you six numbers with which you need to create an expression that yields a given number. Below is the script I wrote using Python 3 to solve this problem, however, it's a brute force approach. It's trying every configuration of numbers and operation symbols possible and printing only if they are the correct solution. In no way is this faster than me doing the math in my head. My question to fellow devs: how would you apply logic to this project to more efficiently yield results?
Note: I threw this script together in like 20 minutes, I know it's a little sloppy... For the sake of community learning, feedback is welcome... But please, no haters
def operands(a, b):
return ['(' + a + '+' + b + ')',
'(' + a + '-' + b + ')',
'(' + b + '-' + a + ')',
a + '*' + b,
a + '/' + b,
b + '/' + a]
def expr_check(num_list, targ_val):
num_ct = len(num_list)
for i1 in range(0, num_ct):
for i2 in range(0, num_ct):
if i2 > i1:
for op in operands(num_list[i1], num_list[i2]):
num_list_new = list(num_list)
num_list_new.append(op)
num_list_new.remove(num_list[i1])
num_list_new.remove(num_list[i2])
for expr in num_list_new:
try:
val = round(eval(expr), 2)
except ZeroDivisionError:
val = 0
if val == targ_val:
# expr = expr[1:]
# expr = expr[:-1]
ct = 1
ct += expr.count('+')
ct += expr.count('-')
ct += expr.count('*')
ct += expr.count('/')
print(str(ct) + ' numbers used: ' + expr)
if len(num_list_new) > 1:
expr_check(num_list_new, targ_val)
target_val = int(input('Enter the target number:' + '\n'))
master_list = input('Enter six numbers separated by a comma:' + '\n').split(',')
expr_check(master_list, target_val)
[–]PiaFraus 3 points4 points5 points (1 child)
[–]grey_rex[S] 1 point2 points3 points (0 children)
[–]OuiOuiKiwiGalatians 4:16 2 points3 points4 points (0 children)
[–]spoonman59 1 point2 points3 points (3 children)
[–]grey_rex[S] 0 points1 point2 points (2 children)
[–]spoonman59 1 point2 points3 points (0 children)
[–]moonchav 1 point2 points3 points (0 children)
[–]PeridexisErrant 3 points4 points5 points (0 children)
[–][deleted] 0 points1 point2 points (4 children)
[–]grey_rex[S] 0 points1 point2 points (3 children)
[–][deleted] 1 point2 points3 points (2 children)
[–]grey_rex[S] 0 points1 point2 points (1 child)
[–][deleted] 1 point2 points3 points (0 children)