Check if a value still remains the same in a While loop Python

后端 未结 4 1826
萌比男神i
萌比男神i 2021-01-27 01:23

I want know if there is a elegant method for looking if a value that continually changes in a while loop can be checked and stop the while loop if the value stops change and rem

4条回答
  •  北恋
    北恋 (楼主)
    2021-01-27 01:59

    A more portable solution would be to make this a class so that an instance holds on to the previous value. I also had a need for a fuzzy match so I included that in the below example.

    class SamenessObserver:
        """An object for watching a series of values to see if they stay the same.
        If a fuzy match is required maxDeviation may be set to some tolerance.
    
        >>> myobserver = SamenessObserver(10)
        >>> myobserver.check(9)
        False
        >>> myobserver.check(9)
        True
        >>> myobserver.check(9)
        True
        >>> myobserver.check(10)
        False
        >>> myobserver.check(10)
        True
        >>> myobserver.check(11)
        False
        >>> myobserver = SamenessObserver(10, 1)
        >>> myobserver.check(11)
        True
        >>> myobserver.check(11)
        True
        >>> myobserver.check(10)
        True
        >>> myobserver.check(12)
        False
        >>> myobserver.check(11)
        True
        >>> 
    
        """
    
        def __init__(self, initialValue, maxDeviation=0):
            self.current = 0
            self.previous = initialValue
            self.maxDeviation = maxDeviation
    
        def check(self, value):
            self.current = value
            sameness = (self.previous - self.maxDeviation) <= self.current <= (self.previous + self.maxDeviation)
            self.previous = self.current
            return sameness
    

提交回复
热议问题