Express a Python loop and a condition mathematically

python

I have the following Python code that I want to express mathematically.

W = 0
for i in range(5):
    if (A > i_1) and ( (A < i_2) or (A < i_3) ):
        W = W + 1

This is a generic problem that I am trying to achieve; looping over some values and checking some condition. If the condition is satisfied, I want to add 1 to the counter (W in this case); otherwise, skip to the next value. How can I express this using a mathematical formula?

To be more specific:

for row in DF1.iterrows():
    pTime = row['A1_time']
    W = 0

    for row2 in DF1.iterrows():
        a1 = row2['A1_time']
        a2 = row2['A2_time']
        a3 = row2['A3_time']

        if (pTime > a1) and ( (pTime < a2) or (pTime < a3) ):
            W = W + 1

Best Answer

To me it looks like you are just computing the cardinality of the set of elements meeting your conditions.

So something like $|\{x : P(x)\}|$ where $P(x)$ means $x $ satisfies your condition.

I can’t be totally sure how to elaborate until you clarify what the index has to do with the inner conditions.


Borrowing a bit of python syntax and using it with set notation, what I'm saying holds above for your latest example:

$|\{(x,y)\in DF1\times DF1: x.a1time > y.a1time \text{ and } x.a1time < max(y.a2time, y.a3time)\}|$

I was able to simplify the OR condition slightly by using max. In fact, this is far closer to how I would do it with real python:

len([(x,y) for x in DF1.iterrows() for y in DF1.iterrows() 
     if x['a1_time'] > y['a1_time'] and x['a1_time'] < max(y['a2_time'],y['a3_time']))])

It can also be compressed a little bit more by using things from the itertools library, but this is more elementary python.

Since it looks like you don't care about the actual entries, just their count, another trick is to just create a list of $1$'s indicating each successful hit, then using sum. This might be a good alternative because you can do it all with generator expressions, conserving memory.

from itertools import product
sum(1 for x,y in product(DF1.iterrows(), DF1.iterrows())
     if x['a1_time'] > y['a1_time'] and x['a1_time'] < max(y['a2_time'],y['a3_time'])))
Related Question