Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: function parameters as a tuple with single output

I have a function in Python which calculates the entropy of a number of parameters which I call ps as follows

def H(*ps): 
    sum = 0.0
    for pi in ps:
        sum = sum - pi*np.log2(pi)
    return sum

I want to be able to pass in multiple parameters as a list or tuple, i.e. H([x]) but this doesn't give the correct result, rather it calculates the value of H(xi) and returns a tuple with each result. I am able to sum each element of the tuple to get the correct result due to the nature of the function but I'd rather be able to have the function give the desired output for convenience. If I enter H(x1, x2, ...) the function gives the correct output.

If anyone has any suggestions please let me know.

Thanks in advance.

EDIT:

Sample input and output:

x = [0.1, 0.2]
print H(0.1, 0.2), H(x)

0.796578428466 [ 0.33219281  0.46438562]
like image 753
knw500 Avatar asked Aug 25 '26 17:08

knw500


1 Answers

Don't unpack via the * operator in your function definition. You are already iterating your list via your for loop. It's natural to use an iterable as a function argument.

def H(ps): 
    x = 0.0
    for pi in ps:
        x = x - pi*np.log2(pi)
    return x

res = H([0.1, 0.2])

print(res)
0.796578428466

In addition, don't shadow the built-in sum, this is poor practice.

like image 78
jpp Avatar answered Aug 28 '26 07:08

jpp