Sunday, December 13, 2015

Python on the go - Application in calculating resistances

Here is a program that calculates resistances in series or  in parallel.


def resistor(l):
    a=raw_input("series or parallel? (s or p)")
    if a== 's':
       sum1 = 0
       for v in l:
                    
           sum1 = sum1 + float(v)
                    
       return sum1

    elif a =='p':
            sum1 = 0
            for v in l:
                    
                    sum1 = sum1 + (1/float(v))
                    
            return 1/sum1


So, how does it work? Firstly, def means that this is a functional program with a list called 'l' so when you run it, you should type 'resistor ([2,3,5])' for example to calculate three resistances of values 2, 3 and 5 ohms.

 In the second line of the program , you will need to  accept variable 'a' as a raw input which may be s or p.  If a='s' to signify that resistances are in series, then the variable suml is first set to 0. In a way  you can think of the variable suml as some kind of container or box where  values (or variables) v can be added to it. Next, there is a  for loop for each variable v  in list 'l' and this for loop will add each variable in 'l' until the end of the list. Once it has reached the end of the list , 'return sum1' displays the value of sum1 and the program exits.

If a=' p',    to signify that resistances are in  parallel, the process is almost the same, only that  the formula for parallel resistances is  different so some changes need to be made near the end.

No comments:

Post a Comment