Help with python functions?

Denis McMahon denismfmcmahon at gmail.com
Tue Oct 1 17:45:24 EDT 2013


On Tue, 01 Oct 2013 10:53:26 -0700, kjakupak wrote:

> I ended up with these. I know they're only like half right...
> I was wondering if any of you had to do this, what would you end up
> with?

> # Question 1.a
> def temp(T, from_unit, to_unit):

I suspect that this doesn't work properly for all cases of from_unit, 
to_unit.

As a general case:

def temp ( T, u1, u2 ):
    # from and to units the same, return T unchanged
    # else use a conversion table
    ct = { (a, b):lambda x: formula, .... }
    return ct[ (u1, u2 ) ]( T )

Note you may need to build in case independence!

> # Question 1.b 
> def comp(T1, u1, T2, u2):

You completely missed the point of my earlier posts, and I suspect the 
reason both these questions were included.

Firstly, consider that if temp (from q1a) works properly you can use temp 
to convert the units of T2 to the units of T1, by calling:

temp( T2, u2, u1 )

q1b can be implemented in one line if temp from q1a works properly!

> # Question 2 
> def P(p_0, t, i):
>    Amount = P(1 + (i/100))
>    return P(1 + (t * i/12))

First calculate the annual interest as 1 + fraction where fraction is 
interest % / 100
The calculate the compounded interest as annual ^ years
Finally multiply the compounded interest by the principal

Mathematically:

principal * ( ( 1 + ( period_interest_% / 100 ) ) ^ periods )

Again, this should be possible as a single line function. All you have to 
do is turn the math into python code.

-- 
Denis McMahon, denismfmcmahon at gmail.com



More information about the Python-list mailing list