pythoninequalities

Solving for single variable inequalities python


I have a simple equation that can easily be solved by hand but I need to solve using python.

Solve for x:

x < 9
x > 4.5
x < 5.6
x > 4.8

So we can easily see x=5 is one of the acceptable solutions. But how would I go about using python to solve for x and return a single value? Thank you.


Solution

  • Depending on the decimal precision you need in your answer, you can increase or decrease the step size in arange below. This is a pythonic way of solving the problem using list comprehension:

    Example:

    import numpy as np
    
    nums = np.arange(0, 6, 0.1)
    answers = [x for x in nums if x < 9 and x > 4.5 and x < 5.6 and x > 4.8]
    
    print(answers)
    

    Output:

    [4.800000000000001, 4.9, 5.0, 5.1000000000000005, 5.2, 5.300000000000001, 5.4, 5.5]
    

    If you only care about integer answers, use an integer step size:

    import numpy as np
    
    nums = np.arange(0, 6, 1)
    answers = [x for x in nums if x < 9 and x > 4.5 and x < 5.6 and x > 4.8]
    
    print(answers)
    

    Output:

    [5]