
Earlier today I had to spend a whole 20 minutes coming up with this function. It’s like a modulo function, but instead of looping back to zero every cycle, it transitions back down to zero. It cycles every 2(n-1) elements. There’s probably a proper name for it, but I can’t figure it out.

In case anyone else would rather google it than spend time figuring it out, here it is:
def ping_pong_mod(i, n): cycle = 2 * (n - 1) i = i % cycle if i >= n: return cycle - i return i
I hope this is helpful to a fellow lazy person in the future.