首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python组合算法-n个可变k固定为2的二项式系数应用

Python组合算法-n个可变k固定为2的二项式系数应用
EN

Code Review用户
提问于 2020-12-27 13:23:39
回答 2查看 83关注 0票数 0

这个问题来自一个真实的用例。我有一个有不同列的数据框架,每个列都包含来自数据源的数据,我想设计一个假设检验来证明数据是否具有相同的平均值。所以我必须计算每两列的Kolmogorov-Smirnov测试。

现在这个问题可以推广到任何组合任务。

因此,我必须实现一个二项式系数,例如

\binom{n}{k}

其中n是列的数目。

K=2

我的问题是:如果存在一种更有效的方法对从列表中提取的变异样本应用函数?以及如何做这个置换(如。给定一个func和一个列表[a,b,c,d]

代码语言:javascript
复制
func(a,b)
func(a,c)
func(a,d)
func(b,c)
func(b,d)
func(c,d)

我创建了一个解决这个问题的算法,但我想知道在Python中是否有更好的方法来解决这个问题。

在我的算法中,我只需将解释性数组中的每个n元素与同一个数组的另一个元素i乘以n!=i,而不是计算统计测试。

代码语言:javascript
复制
to_do=[1,2,3,4,5]
#done will store information on the elements already combined
done=[]
#j will store information on the results of the combination  
j=[]


#iterating over the to_do array
for n in to_do:

  #checking if we already computed the n element  
  if n not in done:
    print(n)
    #taking another i element from the array
    #where n!=i    
    for i in to_do: 
      print(i)
      #if the condition is satisfied       
      if i!=n:
        #combine the two elements        
        m=n*i

        #append the result on the "j" array 
        j.append(m)
    #updating the array with the "done" elements        
    done.append(n)    

print(len(done))
print(len(j))
EN

回答 2

Code Review用户

回答已采纳

发布于 2020-12-27 21:46:18

如果只想要列表的长度,可以将代码缩减为一行:

代码语言:javascript
复制
result = len(to_do) * (len(to_do) - 1)

另外,你的评论至少是过分的。实际上,您应该只使用注释来解释设计选择或复杂的方程/算法。像#if the condition is satisfied这样的注释只会扰乱您的代码。

正如解释过的在评论中一样,需要进行实际的计算。这可以使用itertools.permutations来完成。

代码语言:javascript
复制
import itertools
from typing import List

def func(nums: List[int]) -> List[int]:

    return list(set(
        x * y for x, y in itertools.permutations(nums, 2)
    ))

虽然这并不能避免额外的计算,但这是一个简短而又甜蜜的解决方案。下面是你将如何使用它:

代码语言:javascript
复制
to_do = [1, 2, 3, 4, 5]
func(to_do)
票数 1
EN

Code Review用户

发布于 2020-12-28 14:20:20

我的问题是:如果存在一种更有效的方法对从列表中提取的变异样本应用函数?以及如何做这个置换(如。给定一个函数和一个列表a、b、c、d func(a,b) func(a,c) func(a,d) func(b,c) func(b,d) func(c,d)

看起来你是在寻找组合而不是排列。在这种情况下,使用itertools.combinations

代码语言:javascript
复制
from itertools import combinations

for x, y in combinations(['a', 'b', 'c', 'd'], 2):
    print(x, y)

它打印:

代码语言:javascript
复制
a b
a c
a d
b c
b d
c d

在示例中使用itertools.combinations

代码语言:javascript
复制
from itertools import combinations

todo = [1, 2, 3, 4, 5]
j = [x * y for x, y in combinations(todo, 2)]
票数 1
EN
页面原文内容由Code Review提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://codereview.stackexchange.com/questions/253954

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档