How to toggle a value in Python

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

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

17条回答
  •  太阳男子
    2020-12-07 08:33

    Trigonometric approach, just because sin and cos functions are cool.

    >>> import math
    >>> def generator01():
    ...     n=0
    ...     while True:
    ...         yield abs( int( math.cos( n * 0.5 * math.pi  ) ) )
    ...         n+=1
    ... 
    >>> g=generator01() 
    >>> g.next()
    1
    >>> g.next()
    0
    >>> g.next()
    1
    >>> g.next()
    0
    

提交回复
热议问题