【问题标题】:How to generate the combinations of an array and divide the numbers in each combination by the product of the numbers in the same combination?如何生成数组的组合并将每个组合中的数字除以同一组合中数字的乘积?
【发布时间】:2021-07-06 19:44:46
【问题描述】:

给定一个 N 大小的数组,我想返回该数组的所有可能排列。对于数组的每个排列,我想返回该组合中每个数字的值除以组合中其他数字的总和,包括被除数。

例子:给数组 123,你会找到所有可能的组合,它们是 (1,2) (1,3) (2,3) (1,2,3)。然后将每个组合除以:(1,2) = (1/1+2) = .33333。 (2,1) = (2/1+2) = .66666。

import math
import itertools
from itertools import combinations
import numpy as np
n = int(input("Enter The Amount of Numbers in the List: ")
)
z = []
q = []
for i in range(0,n):
  x = float(input("Enter the numbers: "))
  q.append(x)
h = n+1

permutation_list = []
for i in range(1, len(q)+1):
    permutations = combinations(q, i)
    for perm in permutations:
        perm_prod = 1
        for j in range(len(perm)):
            perm_prod *= perm[j] 
        for j in range(len(perm)-1):
          for k in range(1,len(perm)):
            prod_without_this = perm[j]+perm[k]
            this_num_div_other_nums = perm[j] / prod_without_this
            second_num = perm[k] / prod_without_this   
            permutation_list.append(this_num_div_other_nums)
            permutation_list.append(second_num)
permutation_list[h:]
print(permutation_list)

这是我目前所拥有的,但我无法用长度大于 2 的组合进行划分。任何帮助将不胜感激。

【问题讨论】:

    标签: python arrays numpy combinations


    【解决方案1】:

    您可以这样做,循环遍历组合中每个元素的每个组合。

    from itertools import combinations, chain
    
    l = [1,2,3]
    
    c = list(chain.from_iterable([list(combinations(l,i)) for i in range(2,len(l)+1)]))
    
    
    results = []
    for x in c:
        for n in range(len(x)):
            results.append(x[n]/sum(x))
    

    结果

    [0.3333333333333333,
     0.6666666666666666,
     0.25,
     0.75,
     0.4,
     0.6,
     0.16666666666666666,
     0.3333333333333333,
     0.5]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-12
      • 1970-01-01
      • 1970-01-01
      • 2012-04-26
      相关资源
      最近更新 更多