评估随机长度

时间:2018-06-16 21:35:23

标签: python python-3.x

这是基于问题here

  

输入格式

     

第一行包含一个表示数字的整数 n   列表中的元素。第二行包含 n 空格分隔   整数 a1,a2,a3,... 表示列表的元素。

     

输出格式

     

打印包含所需表达的单行。你可以插入   运算符和操作数之间的空格。

     

注意

     
      
  • 您无权对列表进行置换。
  •   
  • 所有运算符具有相同的优先级并且是左关联的
  •   

在下面的代码中,当我知道输入的长度时,我可以使用嵌套的for循环使其工作,但我的输入可能有5或50或500个元素,我不知道直到运行。嵌套for循环的深度为len(arr)-1,但也许有更好的方法来解决此问题。

我认为,我需要:

  • ops_combos随机长度生成input_ints(不使用permutations lib,按照黑客指示)
  • 评估表达式
  • 并返回评估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])

2 个答案:

答案 0 :(得分:1)

您提供的链接不允许itertools,这意味着您不能更改所提供号码的顺序。

话虽这么说,您需要使用itertools.product或您自己的product实现,因为获得解决方案需要测试所有可能的运算符组合。

函数find_operations返回所有解法的生成器。这允许使用next恢复第一个解决方案或解压缩所有解决方案。

代码

from itertools import product, chain
from operator import add, sub, mul

def apply(numbers, operations):
    """Return the result of applying a list of operations to the list of numbers"""
    ans, *numbers = numbers
    for num, op in zip(numbers, operations):
        ans = op(ans, num)

    return ans

def find_operations(numbers):
    """Return the equation as string that satisfies the res % 101 == 0"""

    # Pair operations and their symbol to later format the result
    operations = {add: '+', sub: '-',  mul: '*'}

    # Loop over all combinations of operations and break when one satisfies
    for ops in product(operations, repeat=len(numbers) - 1):
        if apply(numbers, ops) % 101 == 0:
            # The following lines are just formatting and are not the main focus
            ops = [operations[op] for op in ops]
            nums = [str(x) for x in numbers]

            yield ' '.join(chain(*zip(nums, ops), nums[-1:]))

实施例

solutions = find_operations([22, 79, 21])

print(next(solutions))

输出

22 + 79 * 21

答案 1 :(得分:0)

不使用排列lib对我来说似乎不太合理。但是你可以通过使用生成器来制作等效的嵌套循环:

var adjustHeightToContent = function()
{
    var defaultHeight = 10,
        maxHeight = 150;
    // take padding into account:
    var computedStyle = window.getComputedStyle(this, null),
        paddingTop = computedStyle.getPropertyValue('padding-top'),
        paddingBottom = computedStyle.getPropertyValue('padding-bottom'),
        padding = parseFloat(paddingTop) + parseFloat(paddingBottom);

    jQuery(this).height(defaultHeight); // needed to descrease the height
    var effectiveHeight = this.scrollHeight - padding;
    jQuery(this).height(Math.min(effectiveHeight, maxHeight));
};

您可以使用此迭代器找到您的解决方案:

opers = ['+','*','-']
arr = [55, 3, 45, 33]

def iterate(previous_iterator):
    for previous_list in previous_iterator:
        for oper in opers:
            yield [oper] + previous_list


operator_iterator = [[]]
for i in range(len(arr) - 1):
    operator_iterator = iterate(operator_iterator)

print(list(operator_iterator)) 
# [['+', '+', '+'], ['*', '+', '+'], ['-', '+', '+'], ['+', '*', '+'], ['*', '*', '+'], ['-', '*', '+'], ['+', '-', '+'], ['*', '-', '+'], ['-', '-', '+'], ['+', '+', '*'], ['*', '+', '*'], ['-', '+', '*'], ['+', '*', '*'], ['*', '*', '*'], ['-', '*', '*'], ['+', '-', '*'], ['*', '-', '*'], ['-', '-', '*'], ['+', '+', '-'], ['*', '+', '-'], ['-', '+', '-'], ['+', '*', '-'], ['*', '*', '-'], ['-', '*', '-'], ['+', '-', '-'], ['*', '-', '-'], ['-', '-', '-']]