简体   繁体   中英

Analog of templates in Python

As part of some simulations I'm running I need to output the cumulative distribution of the output of some algorithms:

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()

As the above code shows, I'm running my algorithm 100 times with randomly generated input and then creating a cumulative distribution from the results.

I want to do a similar thing with other algorithms, and in c++ I could write a template class/template function which took a (pointer to a) method as am argument.

I'd like to ask if there is a way in python to create a function/class which produces the output I want, but takes a function as an input, so I avoid duplicating code all over the place.

This is simple to do in Python. You can pass functions (or classes) around like anything else.

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)

I am not sure that i understand the question, but sounds like you want to pass a function as function argument? You can do that right of the bat in python as everything is passed by reference and nothing stops you from passing a reference to a function as an argument.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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