gpt4 book ai didi

python - Python 中模板的模拟

转载 作者:行者123 更新时间:2023-11-30 23:32:32 25 4
gpt4 key购买 nike

作为我正在运行的一些模拟的一部分,我需要输出一些算法输出的累积分布:

tests = []
numtests = 100
for i in range(0, numtests):
#random
zeros = [0] * 1024
ones = [1] * 10
#ones = [randint(0,1023) for _ in range(0,10)]
input = zeros + ones
shuffle(input)
tests.append(HGBSA(input,10))

count = [x[0] for x in tests]
found = [x[1] for x in tests]
found.sort()
num = Counter(found)
freqs = [x for x in num.values()]
cumsum = [sum(item for item in freqs[0:rank+1]) for rank in range(len(freqs))]
normcumsum = [float(x)/numtests for x in cumsum]

print(freqs)
print(cumsum)
print(normcumsum)
print(sorted(num.keys()))

figure(0)
plt.plot(sorted(num.keys()), normcumsum)
plt.xlim(0,100)
plt.show()

如上面的代码所示,我使用随机生成的输入运行算法 100 次,然后根据结果创建累积分布。

我想对其他算法做类似的事情,在 C++ 中我可以编写一个模板类/模板函数,它将一个(指向一个)方法作为参数。

我想问一下Python中是否有一种方法可以创建一个函数/类来产生我想要的输出,但将函数作为输入,这样我就可以避免到处重复代码。

最佳答案

这在 Python 中很简单。您可以像其他任何东西一样传递函数(或类)。

def run_test(test_function):
tests = []
numtests = 100
for i in range(0, numtests):
#random
zeros = [0] * 1024
ones = [1] * 10
#ones = [randint(0,1023) for _ in range(0,10)]
input = zeros + ones
shuffle(input)
tests.append(test_function(input,10))

count = [x[0] for x in tests]
found = [x[1] for x in tests]
found.sort()
num = Counter(found)
freqs = [x for x in num.values()]
cumsum = [sum(item for item in freqs[0:rank+1]) for rank in range(len(freqs))]
normcumsum = [float(x)/numtests for x in cumsum]

print(freqs)
print(cumsum)
print(normcumsum)
print(sorted(num.keys()))

figure(0)
plt.plot(sorted(num.keys()), normcumsum)
plt.xlim(0,100)
plt.show()

run_test(HGBSA)
run_test(SOME_OTHER_FUNCTION)

关于python - Python 中模板的模拟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19300156/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com