'Python - a custom range where after add +1 to max then return minimum

I wonder if there is any function in python like that.

Example 01: For example, if I specify the range from (1,12) integer. Then:

  • if current value is 12 and I add 1, it return 1 (go back to minimum)
  • if current value is 11 and I add 3, it return 2

Example 02: Another example is if I set range from (5, 9). Then:

  • If current value is 8 and I add 2, it return 5
  • If current value is 8 and I add 7, it return 5

I know I can write a self-defined function for that, I am just curious to know if python has that similar function built in

The self-defined function:

def wrap_range(val, nmin, nmax, add_val):
    nrange = nmax - nmin + 1
    remain = add_val % nrange
    val = val + remain
    if val <= nmax:
        return val
    else:
        val = val - nmax + nmin - 1
        return val


Solution 1:[1]

Itertools has the cycle and islice functions that you can use to get what you want -

from itertools import cycle, islice
def repeated_offset(nmin, nmax, start, n):
    rng = range(nmin, nmax + 1)
    start_idx = list(rng).index(start)
    value, *_ = islice(cycle(rng), start_idx + n, start_idx + n + 1)
    return value
repeated_offset(1, 12, 12, 1)
# 1
repeated_offset(1, 12, 11, 3)
# 2
repeated_offset(5, 9, 8, 2)
# 5
repeated_offset(5, 9, 8, 7)
# 5

Solution 2:[2]

What about looping, subtracting while the total value is bigger than the lower boundary, while subtracting range wide.

def loopit(val, the_min, the_max, addition):
    total = val + addition
    diff = the_max - the_min + 1
    if not total > the_min:
        raise ValueError("The total value must be larger then lowest boundary of the range")
    while the_max < total:
        total -= diff

    return total


if __name__ == '__main__':
    print(loopit(12, 1, 12, 1))
    print(loopit(11, 1, 12, 3))
    print(loopit(8, 5, 9, 2))
    print(loopit(8, 5, 9, 7))

output:

1
2
5
5

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mortz
Solution 2 MSH