How to toggle a value in Python

后端 未结 17 946
梦谈多话
梦谈多话 2020-12-07 07:46

What is the most efficient way to toggle between 0 and 1?

相关标签:
17条回答
  • 2020-12-07 08:16

    Here is another non intuitive way. The beauty is you can cycle over multiple values and not just two [0,1]

    For Two values (toggling)

    >>> x=[1,0]
    >>> toggle=x[toggle]
    

    For Multiple Values (say 4)

    >>> x=[1,2,3,0]
    >>> toggle=x[toggle]
    

    I didn't expect this solution to be almost the fastest too

    >>> stmt1="""
    toggle=0
    for i in xrange(0,100):
        toggle = 1 if toggle == 0 else 0
    """
    >>> stmt2="""
    x=[1,0]
    toggle=0
    for i in xrange(0,100):
        toggle=x[toggle]
    """
    >>> t1=timeit.Timer(stmt=stmt1)
    >>> t2=timeit.Timer(stmt=stmt2)
    >>> print "%.2f usec/pass" % (1000000 * t1.timeit(number=100000)/100000)
    7.07 usec/pass
    >>> print "%.2f usec/pass" % (1000000 * t2.timeit(number=100000)/100000)
    6.19 usec/pass
    stmt3="""
    toggle = False
    for i in xrange(0,100):
        toggle = (not toggle) & 1
    """
    >>> t3=timeit.Timer(stmt=stmt3)
    >>> print "%.2f usec/pass" % (1000000 * t3.timeit(number=100000)/100000)
    9.84 usec/pass
    >>> stmt4="""
    x=0
    for i in xrange(0,100):
        x=x-1
    """
    >>> t4=timeit.Timer(stmt=stmt4)
    >>> print "%.2f usec/pass" % (1000000 * t4.timeit(number=100000)/100000)
    6.32 usec/pass
    
    0 讨论(0)
  • 2020-12-07 08:19

    How about an imaginary toggle that stores not only the current toggle, but a couple other values associated with it?

    toggle = complex.conjugate
    

    Store any + or - value on the left, and any unsigned value on the right:

    >>> x = 2 - 3j
    >>> toggle(x)
    (2+3j)
    

    Zero works, too:

    >>> y = -2 - 0j
    >>> toggle(y)
    (-2+0j)
    

    Easily retrieve the current toggle value (True and False represent + and -), LHS (real) value, or RHS (imaginary) value:

    >>> import math
    >>> curr = lambda i: math.atan2(i.imag, -abs(i.imag)) > 0
    >>> lhs = lambda i: i.real
    >>> rhs = lambda i: abs(i.imag)
    >>> x = toggle(x)
    >>> curr(x)
    True
    >>> lhs(x)
    2.0
    >>> rhs(x)
    3.0
    

    Easily swap LHS and RHS (but note that the sign of the both values must not be important):

    >>> swap = lambda i: i/-1j
    >>> swap(2+0j)
    2j
    >>> swap(3+2j)
    (2+3j)
    

    Easily swap LHS and RHS and also toggle at the same time:

    >>> swaggle = lambda i: i/1j
    >>> swaggle(2+0j)
    -2j
    >>> swaggle(3+2j)
    (2-3j)
    

    Guards against errors:

    >>> toggle(1)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: descriptor 'conjugate' requires a 'complex' object but received a 'int'
    

    Perform changes to LHS and RHS:

    >>> x += 1+2j
    >>> x
    (3+5j)
    

    ...but be careful manipulating the RHS:

    >>> z = 1-1j
    >>> z += 2j
    >>> z
    (1+1j) # whoops! toggled it!
    
    0 讨论(0)
  • 2020-12-07 08:20

    I always use:

    p^=True
    

    If p is a boolean, this switches between true and false.

    0 讨论(0)
  • 2020-12-07 08:21

    If you are dealing with an integer variable, you can increment 1 and limit your set to 0 and 1 (mod)

    X = 0  # or X = 1
    X = (X + 1)%2
    
    0 讨论(0)
  • 2020-12-07 08:22

    You can make use of the index of lists.

    def toggleValues(values, currentValue):
        return values[(values.index(currentValue) + 1) % len(values)]
    
    > toggleValues( [0,1] , 1 )
    > 0
    > toggleValues( ["one","two","three"] , "one" )
    > "two"
    > toggleValues( ["one","two","three"] , "three")
    > "one"
    

    Pros: No additional libraries, self.explanatory code and working with arbitrary data types.

    Cons: not duplicate-save. toggleValues(["one","two","duped", "three", "duped", "four"], "duped") will always return "three"

    0 讨论(0)
  • 2020-12-07 08:23

    Just between 1 and 0, do this

    1-x 
    

    x can take 1 or 0

    0 讨论(0)
提交回复
热议问题