这个问题来自一个真实的用例。我有一个有不同列的数据框架,每个列都包含来自数据源的数据,我想设计一个假设检验来证明数据是否具有相同的平均值。所以我必须计算每两列的Kolmogorov-Smirnov测试。
因此,我必须实现一个二项式系数,例如
其中n是列的数目。
K=2
我的问题是:如果存在一种更有效的方法对从列表中提取的变异样本应用函数?以及如何做这个置换(如。给定一个func和一个列表[a,b,c,d]
func(a,b)
func(a,c)
func(a,d)
func(b,c)
func(b,d)
func(c,d)我创建了一个解决这个问题的算法,但我想知道在Python中是否有更好的方法来解决这个问题。
在我的算法中,我只需将解释性数组中的每个n元素与同一个数组的另一个元素i乘以n!=i,而不是计算统计测试。
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))发布于 2020-12-27 21:46:18
如果只想要列表的长度,可以将代码缩减为一行:
result = len(to_do) * (len(to_do) - 1)另外,你的评论至少是过分的。实际上,您应该只使用注释来解释设计选择或复杂的方程/算法。像#if the condition is satisfied这样的注释只会扰乱您的代码。
正如解释过的在评论中一样,需要进行实际的计算。这可以使用itertools.permutations来完成。
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)
))虽然这并不能避免额外的计算,但这是一个简短而又甜蜜的解决方案。下面是你将如何使用它:
to_do = [1, 2, 3, 4, 5]
func(to_do)发布于 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:
from itertools import combinations
for x, y in combinations(['a', 'b', 'c', 'd'], 2):
print(x, y)它打印:
a b
a c
a d
b c
b d
c d在示例中使用itertools.combinations:
from itertools import combinations
todo = [1, 2, 3, 4, 5]
j = [x * y for x, y in combinations(todo, 2)]https://codereview.stackexchange.com/questions/253954
复制相似问题