仅给出子列表的数量(长度可变),显示列表的所有可能分组

时间:2012-01-31 22:59:07

标签: python list math grouping

问题

第1步:给定一个数字列表,只给出所需组的最终数量,生成所有可能的分组(按顺序)。

例如,如果我的数字列表是1到4,并且我想要2个最终组,那么可能性是:

[1], [2,3,4]

[1,2], [3,4]

[1,2,3], [4]

第2步:对这些组执行算术运算。

例如,如果我们选择添加,最终结果将是:

1 + 234 = 235
12 + 34 = 46
123 + 4 = 127

之前的研究和类似问题

我在SO和其他地方看到过很多关于涉及变量金额组的问题的例子,它们使用范围和for循环,la:

print [num_list[i:i+groups] for i in range(0,len(num_list),groups)]

但这与我想要的相反 - 在那里,组的长度本身是固定的,除了最后一组,并且组的数量振荡。

这不是家庭作业,只是我遇到的一个有趣的问题。理想情况下,我需要能够迭代这些单独的子列表以执行数学运算,因此它们也需要被捕获。

我有一种感觉,解决方案将涉及itertools,但我似乎无法弄清楚组合方面的组合。

编辑/扩展第2步

如果我想在每个分区上执行不同的操作,我仍然可以采用相同的方法吗?而不是仅仅指定int。 add ,我能以某种方式执行所有主要4个操作的另一个组合吗?即:

symbol_list = ['+','-','*','/']
for op in symbol_list:
   #something

我最终会有以下可能性:

1 + 2 * 34
1 * 2 - 34
1 / 2 + 34
etc.

操作顺序可以忽略

最终解决方案

#!/usr/bin/env python

import sys
from itertools import combinations, chain, product

# fixed vars
num_list = range(_,_) # the initial list
groups = _ # number of groups
target = _ # any target desired
op_dict = {'+': int.__add__, '-': int.__sub__,
           '*': int.__mul__, '/': int.__div__}

def op_iter_reduce(ops, values):
    op_iter = lambda a, (i, b): op_dict[ops[i]](a, b)
    return reduce(op_iter, enumerate(values[1:]), values[0])

def split_list(data, n):
    for splits in combinations(range(1, len(data)), n-1):
        result = []
        prev = None
        for split in chain(splits, [None]):
            result.append(data[prev:split])
            prev = split
        yield result

def list_to_int(data):
    result = 0
    for h, v in enumerate(reversed(data)):
        result += 10**h * v
    return result

def group_and_map(data, num_groups):
    template = ['']*(num_groups*2 - 1) + ['=', '']
    for groups in split_list(data, num_groups):
        ints = map(list_to_int, groups)
        template[:-2:2] = map(str, ints)
        for ops in product('+-*/', repeat=num_groups-1):
            template[1:-2:2] = ops
            template[-1] = str(op_iter_reduce(ops, ints))
            if op_iter_reduce(ops, ints) == target:
                print ' '.join(template)

group_and_map(num_list, groups)

3 个答案:

答案 0 :(得分:7)

Raymond Hettinger has written a recipe用于查找可迭代的所有分区到n组:

import itertools
import operator

def partition_indices(length, groups, chain = itertools.chain):
    first, middle, last = [0], range(1, length), [length]    
    for div in itertools.combinations(middle, groups-1):
        yield tuple(itertools.izip(chain(first, div), chain(div, last)))

def partition_into_n_groups(iterable, groups, chain = itertools.chain):
    # http://code.activestate.com/recipes/576795/
    # author: Raymond Hettinger
    # In [1]: list(partition_into_n_groups('abcd',2))
    # Out[1]: [('a', 'bcd'), ('ab', 'cd'), ('abc', 'd')]
    s = iterable if hasattr(iterable, '__getitem__') else tuple(iterable)
    for indices in partition_indices(len(s), groups, chain):
        yield tuple(s[slice(*x)] for x in indices)

def equations(iterable, groups):
    operators = (operator.add, operator.sub, operator.mul, operator.truediv)
    strfop = dict(zip(operators,'+-*/'))
    for partition in partition_into_n_groups(iterable, groups):
        nums_list = [int(''.join(map(str,item))) for item in partition]
        op_groups = itertools.product(operators, repeat = groups-1)
        for op_group in op_groups:
            nums = iter(nums_list)
            result = next(nums)
            expr = [result]
            for op in op_group:
                num = next(nums)
                result = op(result, num)
                expr.extend((op, num))
            expr = ' '.join(strfop.get(item,str(item)) for item in expr)
            yield '{e} = {r}'.format(e = expr, r = result)

for eq in equations(range(1,5), groups = 2):
    print(eq)

产量

1 + 234 = 235
1 - 234 = -233
1 * 234 = 234
1 / 234 = 0.0042735042735
12 + 34 = 46
12 - 34 = -22
12 * 34 = 408
12 / 34 = 0.352941176471
123 + 4 = 127
123 - 4 = 119
123 * 4 = 492
123 / 4 = 30.75

答案 1 :(得分:6)

第1步:我发现想要将列表拆分成这样的组的最简单方法是尝试获取拆分位置的组合。这是一个实现:

def split_list(data, n):
    from itertools import combinations, chain
    for splits in combinations(range(1, len(data)), n-1):
        result = []
        prev = None
        for split in chain(splits, [None]):
            result.append(data[prev:split])
            prev = split
        yield result

>>> list(split_list([1, 2, 3, 4], 2))
[[[1], [2, 3, 4]], [[1, 2], [3, 4]], [[1, 2, 3], [4]]]
>>> list(split_list([1, 2, 3, 4], 3))
[[[1], [2], [3, 4]], [[1], [2, 3], [4]], [[1, 2], [3], [4]]]

第2步:首先,您需要将[[1], [2, 3, 4]]之类的列表转换为[1, 234]之类的列表。您可以使用以下功能执行此操作:

def list_to_int(data):
    result = 0
    for i, v in enumerate(reversed(data)):
        result += 10**i * v
    return result

>>> map(list_to_int, [[1], [2, 3], [4, 5, 6]])
[1, 23, 456]

现在,您可以使用reduce()

在结果列表中执行操作
>>> import operator
>>> reduce(operator.add, [1, 23, 456])  # or int.__add__ instead of operator.add
480

完整解决方案:基于不同运营商的编辑参考需求:

def op_iter_reduce(ops, values):
    op_dict = {'+': int.__add__, '-': int.__sub__,
               '*': int.__mul__, '/': int.__div__}
    op_iter = lambda a, (i, b): op_dict[ops[i]](a, b)
    return reduce(op_iter, enumerate(values[1:]), values[0])

def group_and_map(data, num_groups):
    from itertools import combinations_with_replacement
    op_dict = {'+': int.__add__, '-': int.__sub__,
               '*': int.__mul__, '/': int.__div__}
    template = ['']*(num_groups*2 - 1) + ['=', '']
    op_iter = lambda a, (i, b): op_dict[ops[i]](a, b)
    for groups in split_list(data, num_groups):
        ints = map(list_to_int, groups)
        template[:-2:2] = map(str, ints)
        for ops in combinations_with_replacement('+-*/', num_groups-1):
            template[1:-2:2] = ops
            template[-1] = str(op_iter_reduce(ops, ints))
            print ' '.join(template)

>>> group_and_map([1, 2, 3, 4], 2)
1 + 234 = 235
1 - 234 = -233
1 * 234 = 234
1 / 234 = 0
12 + 34 = 46
12 - 34 = -22
12 * 34 = 408
12 / 34 = 0
123 + 4 = 127
123 - 4 = 119
123 * 4 = 492
123 / 4 = 30

如果您使用的是Python 2.6或更低版本且itertools.combinations_with_replacement()不可用,则可以使用配方linked here

答案 2 :(得分:3)

第1步:

我研究了所有可能的索引组合:

from itertools import combinations

def cut(lst, indexes):
    last = 0
    for i in indexes:
        yield lst[last:i]
        last = i
    yield lst[last:]


def generate(lst, n):
    for indexes in combinations(list(range(1,len(lst))), n - 1):
        yield list(cut(lst, indexes))

示例:

for g in generate([1, 2, 3, 4, 5], 3):
    print(g)
"""
[[1], [2], [3, 4, 5]]
[[1], [2, 3], [4, 5]]
[[1], [2, 3, 4], [5]]
[[1, 2], [3], [4, 5]]
[[1, 2], [3, 4], [5]]
[[1, 2, 3], [4], [5]]
"""

第2步:

首先,我们必须转换数字中的数字组:

for g in generate(list(range(1,6)), 3):
    print([int(''.join(str(n) for n in n_lst)) for n_lst in g])
"""
[1, 2, 345]
[1, 23, 45]
[1, 234, 5]
[12, 3, 45]
[12, 34, 5]
[123, 4, 5]
"""

然后使用reduceoperator执行算术:
(虽然最后一个子步骤与您的问题无关)

from functools import reduce
import operator
op = operator.mul

for g in generate(list(range(1,6)), 3):
    converted = [int(''.join(str(n) for n in n_lst)) for n_lst in g]
    print(reduce(op, converted))
"""
690
1035
1170
1620
2040
2460
"""