Learning Python how would I rewrite this code

need assistance - Modify this code to introduce a new function for the commonalities in these expressions and change the calculations to calls of that function.

import math

def compute_aqhi(o3, no2, pm2_5):
o3_contribution = math.e ** (0.000537 * o3) - 1
no2_contribution = math.e ** (0.000871 * no2) - 1
pm2_5_contribution = math.e ** (0.000487 * pm2_5) - 1
pollutant_sum = o3_contribution + no2_contribution + pm2_5_contribution
return (1000 / 10.4) * pollutant_sum

result = compute_aqhi(75.0, 5.0, 57.0)


Is this about the Canadian Air Quality Health Index?

First, note what varies between what is to the right of the = operator on these three lines:

    o3_contribution = math.e ** (0.000537 * o3) - 1
    no2_contribution = math.e ** (0.000871 * no2) - 1
    pm2_5_contribution = math.e ** (0.000487 * pm2_5) - 1

There are two variables. Let’s name them coeff and pollutant. It follows, then, that the new function, which we can name contribution, will include those names as its two parameters. Accordingly, we can have this as a function header:

def contribution(coeff, pollutant):

Then, adapt the expression to the right of the = operator on one of the three lines posted above to become the body of the function. That gives us:

  return math.e ** (coeff * pollutant) - 1

So, what still needs to be done is to assemble the parts of the new function, add it to your program, and replace the three lines displayed above, to make appropriate calls to the new function.

Please give it a try, and post your resulting code, so that we can continue to help.

If you are writing this as a learning exercise, it is fine, but if you
are planning to use hypotenuse() for real in a program, you should
prefer Python’s version:

import math
c = math.hypot(a, b)

which will probably be faster and more accurate.


In your version, you have

def hypotenuse(a, b):
    a_squared = square(a)
    b_squared = square(b)
    return sqrt(a_squared + b_squared)

and you want to get rid of the variables ‘a_squared’ and ‘b_squared’.

Find how a_squared is calculated, and use that directly inside the call
to sqrt. Same for b_squared:

def hypotenuse(a, b):
    return sqrt(square(a) + square(b))