以下是关于这个问题的翻译:
这个问题的基础在这里:
输入格式
第一行包含一个整数n,表示列表中元素的数量。第二行包含n个以空格分隔的整数a1, a2, a3, ...,表示列表的元素。
输出格式
打印一行内容为所需表达式的单个行。您可以在运算符和操作数之间插入空格。
注意
- 不允许对列表进行排列。
- 所有运算符具有相同的优先级并且是左结合的。
在我的下面的代码中,当我知道输入的长度时,可以使用嵌套的for
循环使其正常工作,但是我的输入可能有5个、50个或500个元素,直到运行时我才知道这一点。嵌套的for
循环的深度将是len(arr)-1
,但也许有更好的方法来解决这个问题。
我认为我需要:
- 为随机长度的
input_ints
生成ops_combos
(不使用permutations
库,根据hackerrank的说明) - 求解表达式
- 并返回第一个求值为
True
的表达式。
有什么建议吗?
import operator
ops = { "+": operator.add, "*": operator.mul, "-": operator.sub } # etc.
opers = ['+','*','-']
arr = [55, 3, 45, 33, 25] # needs to work for any length of arr
# Generate every len(arr)-1 combo of the 3 symbols (include repetition)
for i in range(3):
for j in range(3):
for k in range(3):
for l in range(3):
x = ops[ opers[i] ]( arr[0], arr[1] ) # first number (0), first operator (i), second number (1)
x = ops[ opers[j] ]( x, arr[2] ) # x, second operator (j), third number (2)
x = ops[ opers[k] ]( x, arr[3] ) # x, third operator (k), fourth number (3)
x = ops[ opers[l] ]( x, arr[4] ) # x, fourth operator (l), fifth number (4)
if x % 101 == 0:
print (arr[0], opers[i], arr[1], opers[j], arr[2], opers[k], arr[3], opers[l], arr[4])