pythonfunctionweighting

How can I create a Python function with variable arguments


I want to create a weighting function in Python. However the amount of weighting varies and I need the function to have optional parameters (for instance, you could find the cost of weightA and weightB, but you could also find all of the above.

The basic function looks like this:

weightA = 1
weightB = 0.5
weightC = 0.33
weightD = 2

cost = 70

volumeA = 100
volumeB = 20
volumeC = 10
volumeD = 5


def weightingfun (cost, weightA, weightB, volumeA, volumeB):
    costvolume = ((cost*(weightA+weightB))/(weightA*volumeA+weightB*volumeB))
    return costvolume

How can I change the function so that I could for example also weight volume C and volume D?

Thanks ahead!


Solution

  • This can be done very simply with operations on tuples or lists:

    import operator
    def weightingfun(cost, weights, volumes):
        return cost*sum(weights)/sum(map( operator.mul, weights, volumes))
    
    weights = (1, 0.5, 0.33, 2)
    volumes = (100, 20, 10, 5)
    print weightingfun(70, weights, volumes)