简体   繁体   English

返回Python中数字列表的不同乘法组合

[英]Return the different multiplicative combinations of a list of numbers in Python

I have a list of numbers and I wish to return a 2D list, preferably ordered from biggest to smallest (although I can do this afterwards), of all the possible combinations of multiplication (to yield the product of the original list) using all the elements of the list, without duplicates. 我有一个数字列表,我希望返回一个2D列表,最好从最大到最小(尽管我之后可以这样做),所有可能的乘法组合(以产生原始列表的产品)使用所有列表的元素,没有重复。 That is, if I have a list of [1, 2, 3] I want it to return 也就是说,如果我有一个[1,2,3]的列表,我希望它返回

[[3, 2, 1], [3, 2], [6, 1], [6]]

without duplicates or equivalent lists, as seen above ([2,3] does not appear). 没有重复或等效列表,如上所示([2,3]没有出现)。

The reason for this is to find all the ways to multiply together the prime factorisation of a number. 这样做的原因是找到将数字的素数因子化相乘的所有方法。 That is, from the prime factors of 24 (2, 2, 2, 3) I want it to return 也就是说,从24(2,2,2,3)的素数因子我希望它返回

[[3, 2, 2, 2], [4, 3, 2], [6, 4], [6, 2, 2], [8, 3], [12, 2], [24]]

I hope I have made myself clear, I wasn't sure how to phrase this question correctly. 我希望我已经说清楚,我不确定如何正确地表达这个问题。

One way you can do this: Use two nested loops to multiply each number in the list with each other number, then recurse on that new list. 一种方法是:使用两个嵌套循环将列表中的每个数字与其他数字相乘,然后递归到新的列表中。 This is not very efficient, as you will have tons of duplicate function calls (eg for multiplying the 3 in (3, 2, 2, 2) with any of the three 2 s, but this can be helped with a bit of memoization (unfortunately, this means we have to convert between lists and tuples a lot). Still, for larger inputs it's not very fast. 这不是很有效,因为你将有大量重复的函数调用(例如,将3英寸(3, 2, 2, 2) 3,2,2,2 (3, 2, 2, 2)与三个2的任何一个相乘,但这可以通过一些记忆来帮助(不幸的是,这意味着我们必须在列表和元组之间进行很多转换。但是,对于较大的输入,它并不是很快。

def memo(f):
    f.cache = {}
    def _f(*args, **kwargs):
        if args not in f.cache:
            f.cache[args] = f(*args, **kwargs)
        return f.cache[args]
    return _f

@memo
def mult_comb(factors):
    result = set()
    result.add(tuple(sorted(factors)))
    for i, f1 in enumerate(factors):
        factors2 = list(factors[:i] + factors[i+1:])
        for k in range(i, len(factors2)):
            factors2[k] *= f1
            result.update(mult_comb(tuple(factors2)))
            factors2[k] /= f1
    return result

Example: 例:

>>> mult_comb((3,2,2,2))
set([(4, 6), (3, 8), (2, 12), (2, 3, 4), (24,), (2, 2, 6), (2, 2, 2, 3)])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM