Search code examples
pythonfunctionboolean-logic

x (> if bool else <) y


I'm looking for a logic to use a function with different operators.

Is there a way to implement the logic to use a boolean to determine the operator in the comparison? something along the lines of

while df["column"][i + period] (> if bool_var else <=) min(df["column"])

Edit: can anyone explicitly show me how that logic would be implemented with the operator module?

while operator.gt(a, b) if bool_var else operator.eq(a, b): ?

Solution

  • To avoid duplicated blocks in your if/else branching all you need is to change your while statement basing on positive flag and comparison operator created by operator module:

    from operator import eq, gt
    
    def check_trends(df, set_lenght, positive=True, get_index=False):
        periods = []
        op = gt if positive else eq  # select operator
        
        for i in range(len(df.index)):
            period = 0
            while op(df["perc_btc"][i + period], min(df["perc_btc"])):
                if len(df.index) <= (i + period + 1):
                    break
                period += 1
            if period > set_lenght:
                periods.append([i, period])
                if get_index:
                    return [i, i + period]  # returns the last starting point
        return periods