3

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]
3
  • Please add sample input and output Commented Jul 3, 2018 at 13:58
  • @TaohidulIslam Updated Commented Jul 3, 2018 at 13:59
  • Alternatively, you can unpack x in H(x) with H(*x). Commented Jul 3, 2018 at 14:01

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

Comments

1

You can pass the argument as a list or tuple. You can avoid using unpack trick here.

def H(ps): #updated, not asterisk 
    my_sum = 0.0
    for pi in ps:
        my_sum = my_sum - pi*np.log2(pi)
    return my_sum
x = [0.1, 0.2]
print (H([0.1, 0.2])) #argument as list
print(H(x)) #argument as list

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.