How to toggle a value in Python

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

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

17条回答
  •  -上瘾入骨i
    2020-12-07 08:12

    Switching between -1 and +1 can be obtained by inline multiplication; used for calculation of pi the 'Leibniz' way (or similar):

    sign = 1
    result = 0
    for i in range(100000):
        result += 1 / (2*i + 1) * sign
        sign *= -1
    print("pi (estimate): ", result*4)
    

提交回复
热议问题