Home > front end >  How do I add a number to a range than add a interger to it
How do I add a number to a range than add a interger to it

Time:11-07

I want to add my number to a range of numbers. After I want to add a number to my original number while staying in the range provided. If the number I add too my original numbers is greater than the range provided I want it to just start at the beginning and keep adding. Any idea how this is done, my code below adds to 97, but I want it to be 67.

big = range(60,90)
num = 84
if num in big:
    print(num   13)

CodePudding user response:

Your description is a bit unclear, but it seems like you're looking for modular arithmetic. Try this:

lower_bound = 60
upper_bound = 90
num = 84
num  = 13
reduced_num = (num - lower_bound)%(upper_bound-lower_bound)   lower_bound

The % operator takes the remainder when dividing by the given number, so if you find by how much num is above 60, then take 0 of that number, then add the 60 back, you'll get a number between 60 and 90.

CodePudding user response:

If you want to be able to do math in a finite field, you need more than just a range. You need that range to be tied to your value and applied to it when you use an arithmetic operator with your value.

Here is a class that represents a value with modular arithmetic applied to it.

class ModularValue:
    """Represents a value in a finite field of integers.

    The field is closed over the standard arithmetic operators,
    meaning that if the value should exceed the field in either
    direction, it will 'wrap around' to the other side.
    """
    def __init__(self, value, lo, hi):
        self.lo = lo
        self.hi = hi
        self.value = self.clamp(value)

    @staticmethod
    def fromrange(value, rng):
        return ModularValue(value, rng.start, rng.stop)

    def __repr__(self):
        return f"ModularValue({self.value}, {self.lo}, {self.hi})"

    def __str__(self):
        return str(self.value)

    def clamp(self, value):
        return (value % (self.hi - self.lo))   self.lo

    def __add__(self, addend):
        return ModularValue(self.clamp(self.value   addend), self.lo, self.hi)

    def __sub__(self, minuend):
        return ModularValue(self.clamp(self.value - minuend), self.lo, self.hi)

I have only implemented addition and subtraction. I leave the implementation of the other arithmetic operators as an exercise for the reader.

You can create a value with the start and stop values of the range, or you can create one off of a range object with the static method, as follows:

m = ModularValue(84, 60, 90)
# or
m = ModularValue.fromrange(84, range(60, 90))

If you then add 13 to this value, you will get 67 as expected.

>>> print(m   13)
67
  • Related