@lyubomyr83 Something like this?
# -*- coding: utf-8 -*-
"""
Test solution for https://forum.omz-software.com/topic/6159/function-for-recognize-quantity-of-unique-combinations
"""
import operator
OPERATORS = {
"+": operator.add,
"-": operator.sub,
"*": operator.mul,
"×": operator.mul,
}
def eval_eq(a, op, b):
return OPERATORS[op](a, b)
def uniques_col(operators, max):
if len(operators) == 0:
# we could also just return (max - 1)
raise ValueError("No operators given!")
elif len(operators) > 1:
# the code in the question makes it look like we should add
# the number of individual operator combinations if multiple
# operators are given.
n = 0
for op in operators:
n += uniques_col(op, max)
return n
else:
combinations = []
for a in range(max, 0, -1):
# for a in range(1, max + 1):
for b in range(max, 0, -1):
# for b in range(1, max + 1):
res = eval_eq(a, operators, b)
if res > max:
# should this be result >= max?
continue
if res < 0:
# result cant be under 0
continue
comb = (a, operators, b)
print(comb)
if comb not in combinations:
combinations.append(comb)
return len(combinations)
if __name__ == "__main__":
testdata = [
# format: operators, max, expected
("-", 2, 3),
("+", 2, 1),
("+-", 2, 4),
("+-", 3, 9),
("+-*", 3, None),
]
for ops, m, exp in testdata:
n = uniques_col(ops, m)
print("uniques_col({m}, '{o}') -> {r}; expected {e}".format(m=m, o=ops, r=n, e=exp))
This produced this output:
(2, '-', 2)
(2, '-', 1)
(1, '-', 1)
uniques_col(2, '-') -> 3; expected 3
(1, '+', 1)
uniques_col(2, '+') -> 1; expected 1
(1, '+', 1)
(2, '-', 2)
(2, '-', 1)
(1, '-', 1)
uniques_col(2, '+-') -> 4; expected 4
(2, '+', 1)
(1, '+', 2)
(1, '+', 1)
(3, '-', 3)
(3, '-', 2)
(3, '-', 1)
(2, '-', 2)
(2, '-', 1)
(1, '-', 1)
uniques_col(3, '+-') -> 9; expected 9
(2, '+', 1)
(1, '+', 2)
(1, '+', 1)
(3, '-', 3)
(3, '-', 2)
(3, '-', 1)
(2, '-', 2)
(2, '-', 1)
(1, '-', 1)
(3, '*', 1)
(2, '*', 1)
(1, '*', 3)
(1, '*', 2)
(1, '*', 1)
uniques_col(3, '+-*') -> 14; expected None
Your question is kind of hard to understand, so I am not sure this solution is correct...