How to toggle a value in Python

后端 未结 17 968
梦谈多话
梦谈多话 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
    

提交回复
热议问题