在0和之间切换的最有效方法是什么1?
在0和之间切换的最有效方法是什么1?
Answers:
如果值是布尔值,最快的方法是使用not运算符:
>>> x = True
>>> x = not x # toggle
>>> x
False
>>> x = not x # toggle
>>> x
True
>>> x = not x # toggle
>>> x
False
如果值是数字,则从总数中减去是切换值的一种简单快捷的方法:
>>> A = 5
>>> B = 3
>>> total = A + B
>>> x = A
>>> x = total - x # toggle
>>> x
3
>>> x = total - x # toggle
>>> x
5
>>> x = total - x # toggle
>>> x
3
如果该值在0和1之间切换,则可以使用按位异或:
>>> x = 1
>>> x ^= 1
>>> x
0
>>> x ^= 1
>>> x
1
该技术可以推广到任意一对整数。异或一步被替换为预异常数:
>>> A = 205
>>> B = -117
>>> t = A ^ B # precomputed toggle constant
>>> x = A
>>> x ^= t # toggle
>>> x
-117
>>> x ^= t # toggle
>>> x
205
>>> x ^= t # toggle
>>> x
-117
(此想法由Nick Coghlan提交,后来由@zxxc推广。)
如果值是可哈希的,则可以使用字典:
>>> A = 'xyz'
>>> B = 'pdq'
>>> d = {A:B, B:A}
>>> x = A
>>> x = d[x] # toggle
>>> x
'pdq'
>>> x = d[x] # toggle
>>> x
'xyz'
>>> x = d[x] # toggle
>>> x
'pdq'
最慢的方法是使用条件表达式:
>>> A = [1,2,3]
>>> B = [4,5,6]
>>> x = A
>>> x = B if x == A else A
>>> x
[4, 5, 6]
>>> x = B if x == A else A
>>> x
[1, 2, 3]
>>> x = B if x == A else A
>>> x
[4, 5, 6]
如果您有两个以上的值,则itertools.cycle()函数提供了一种通用的快速方法来在连续的值之间进行切换:
>>> import itertools
>>> toggle = itertools.cycle(['red', 'green', 'blue']).next
>>> toggle()
'red'
>>> toggle()
'green'
>>> toggle()
'blue'
>>> toggle()
'red'
>>> toggle()
'green'
>>> toggle()
'blue'
请注意,在Python 3中,next()方法已更改为__next__(),因此第一行现在将写为toggle = itertools.cycle(['red', 'green', 'blue']).__next__
.next()替换为全局next()函数。上面的示例为:toggle = itertools.cycle(...); next(toggle)
toggle = itertools.cycle(['red', 'green', 'blue']) next(toggle)
a和b使用x = x ^ (a ^ b)。
int(not 0)和int(not 1)... hrmmm
我一直使用:
p^=True
如果p是布尔值,则在true和false之间切换。
p无需两次引用即可使用此方法!!构想一下,如果您要在很长的参考时间内切换一个值。
^=是按位异或
这是另一种不直观的方法。优点是您可以循环多个值,而不仅仅是两个[0,1]
对于两个值(切换)
>>> x=[1,0]
>>> toggle=x[toggle]
对于多个值(例如4)
>>> x=[1,2,3,0]
>>> toggle=x[toggle]
我没想到这个解决方案也几乎是最快的
>>> 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
在1到0之间执行此操作
1-x
x可以取1或0
True和False实际上都是整数,尽管具有令人惊讶的冗长__str__()方法的整数x也可以是Trueor Falsehere。不过,您将获得1或0的返还。
三角法,仅仅是因为sin和cos函数很酷。
>>> 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
令人惊讶的是,没有人提到好的旧除法模2:
In : x = (x + 1) % 2 ; x
Out: 1
In : x = (x + 1) % 2 ; x
Out: 0
In : x = (x + 1) % 2 ; x
Out: 1
In : x = (x + 1) % 2 ; x
Out: 0
请注意,它等效于x = x - 1,但是取模技术的优点是组的大小或间隔的长度可以大于2个元素,从而为循环提供了类似于轮询交错的方案。
现在只需要2,切换就可以短一些(使用按位运算符):
x = x ^ 1
一种切换方式是使用多重分配
>>> a = 5
>>> b = 3
>>> t = a, b = b, a
>>> t[0]
3
>>> t = a, b = b, a
>>> t[0]
5
使用itertools:
In [12]: foo = itertools.cycle([1, 2, 3])
In [13]: next(foo)
Out[13]: 1
In [14]: next(foo)
Out[14]: 2
In [15]: next(foo)
Out[15]: 3
In [16]: next(foo)
Out[16]: 1
In [17]: next(foo)
Out[17]: 2
使用异常处理程序
>>> def toogle(x):
... try:
... return x/x-x/x
... except ZeroDivisionError:
... return 1
...
>>> x=0
>>> x=toogle(x)
>>> x
1
>>> x=toogle(x)
>>> x
0
>>> x=toogle(x)
>>> x
1
>>> x=toogle(x)
>>> x
0
好吧,我是最糟糕的:
import math
import sys
d={1:0,0:1}
l=[1,0]
def exception_approach(x):
try:
return x/x-x/x
except ZeroDivisionError:
return 1
def cosinus_approach(x):
return abs( int( math.cos( x * 0.5 * math.pi ) ) )
def module_approach(x):
return (x + 1) % 2
def subs_approach(x):
return x - 1
def if_approach(x):
return 0 if x == 1 else 1
def list_approach(x):
global l
return l[x]
def dict_approach(x):
global d
return d[x]
def xor_approach(x):
return x^1
def not_approach(x):
b=bool(x)
p=not b
return int(p)
funcs=[ exception_approach, cosinus_approach, dict_approach, module_approach, subs_approach, if_approach, list_approach, xor_approach, not_approach ]
f=funcs[int(sys.argv[1])]
print "\n\n\n", f.func_name
x=0
for _ in range(0,100000000):
x=f(x)
怎么样一个假想的切换,存储不仅是当前切换,但与之相关的其他几个值?
toggle = complex.conjugate
在左侧存储任何+或-值,在右侧存储任何无符号的值:
>>> x = 2 - 3j
>>> toggle(x)
(2+3j)
零也起作用:
>>> y = -2 - 0j
>>> toggle(y)
(-2+0j)
轻松检索当前的切换值(True并False表示+和-),LHS(实数)值或RHS(虚数)值:
>>> 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
轻松交换LHS和RHS(但请注意,两个值的符号一定不重要):
>>> swap = lambda i: i/-1j
>>> swap(2+0j)
2j
>>> swap(3+2j)
(2+3j)
轻松交换LHS和RHS 并同时切换:
>>> swaggle = lambda i: i/1j
>>> swaggle(2+0j)
-2j
>>> swaggle(3+2j)
(2-3j)
防止错误:
>>> toggle(1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: descriptor 'conjugate' requires a 'complex' object but received a 'int'
对LHS和RHS进行更改:
>>> x += 1+2j
>>> x
(3+5j)
...但是要小心操作RHS:
>>> z = 1-1j
>>> z += 2j
>>> z
(1+1j) # whoops! toggled it!
如果要处理整数变量,则可以递增1并将其限制为0和1(mod)
X = 0 # or X = 1
X = (X + 1)%2
您可以使用的index的list秒。
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"
优点:无需其他库,自我解释代码并可以处理任意数据类型。
缺点:不重复保存。
toggleValues(["one","two","duped", "three", "duped", "four"], "duped")
永远会回来"three"