Function which measures time M times

60 Views Asked by At

I am to measure how much time does it take for the function below to represent: C in range [0, 10] with the numbers in list N. (M measurements for each C).

import itertools
def amount(C):
    N = [1, 2, 5]
    #N = list(N)
    N = sorted(N)
    while C < max(N):
        N.remove(max(N))
    res = []
    for i in range(1, C):
        for j in list(itertools.combinations_with_replacement(N, i)):
            res.append(sum(list(j)))
    m = 0
    for z in range (0, len(res)):
        if res[z] == C:
            m += 1
    if N[0] == 1:
        return m + 1 
    else:
       return m 

EDITED:

import itertools
def amount(C):
    N = [1, 2, 5]
    res = []
    for i in range(1, C):
        for j in list(itertools.combinations_with_replacement(N, i)):
            res.append(sum(list(j)))
    m = 0
    for z in range (0, len(res)):
        if res[z] == C:
            m += 1
    if N[0] == 1:
        return m + 1 
    else:
       return m

I would like to make 10 measurements and then take for example median of all those measurements.

There is my code but something unfortunately doesn't work properly and I have no idea what is wrong:

import time
def time_counter(amount, n=11, M=11):
    res = list(range(n))
    def count_once():
        start = time.perf_counter()
        amount(res)
        return time.perf_counter() - start
    return [count_once() for m in range(M)]
1

There are 1 best solutions below

6
On BEST ANSWER

You are again passing a list and trying to do range(1,C) where C is a list

Here is how your program should be

import itertools
import time    
def amount(C):
    N = [1, 2, 5]
    res = []
    for i in range(1, C):
        for j in list(itertools.combinations_with_replacement(N, i)):
            res.append(sum(list(j)))
    m = 0
    for z in range (0, len(res)):
        if res[z] == C:
            m += 1
    if N[0] == 1:
        return m + 1 
    else:
       return m

def time_counter(amount, n=11, M=11):
    res = list(range(n))
    def count_once(c):
        start = time.perf_counter()
        amount(c)
        return time.perf_counter() - start
    return [count_once(m) for m in range(M)]

#testing
print(time_counter(amount))