Search code examples
pythonappendequationdefinition

Python (repeated values with append)


I have the following formula Q = Square root of [(2 * C * D)/H] And I would like to input 100,150,180 so the output i want is 18,22,24

so my code is

import math
c=50
h=30
value=[]
def equation(a1,b1,c1):
    for i in (a1,b1,c1):
        value.append(int(math.sqrt(2*c*a1/h)))
        value.append(int(math.sqrt(2*c*b1/h)))
        value.append(int(math.sqrt(2*c*c1/h)))
        print (value)

when I input equation(100,150,180), why is the output following?

[18, 12, 24]
[18, 12, 24, 18, 12, 24]
[18, 12, 24, 18, 12, 24, 18, 12, 24]

How do i change the code so i get only

[18, 12, 24]

Solution

  • loop on values only to apply the same formula, in a list comprehension, also don't print the result, just return it (and print it in the caller if needed):

    import math
    c=50
    h=30
    def equation(a1,b1,c1):
        return [int(math.sqrt(2*c*x/h)) for x in (a1,b1,c1)]
    
    print(equation(100,150,180))
    

    result:

    [18, 22, 24]
    

    (this saves this kind of loop/where do I define my return value errors and a lot of copy/paste)

    Variant with variable arguments (same calling syntax, saves argument packing & unpacking since all arguments get the same treatment):

    def equation(*args):
        return [int(math.sqrt(2*c*x/h)) for x in args]