要重现此问题,请在repl.it中运行此命令,并在出现提示时输入“cNOT”(不带引号)。在此之后,它应该询问你想要第二个量子位的门,相反,它再次询问你给出的“cNOT”作为答案的相同问题。
import numpy as np
def target(qstat):
typegat2 = input("Which gate is this target qubit for? See list of two qubit gates at the top.")
if typegat2 == "cNOT":
carray = np.array([[0,1],[1,0]])
if np.array_equal(mem1, [0,1]) == True:
return qstat
elif np.array_equal(mem1, [1,0]) == True:
return np.dot(qstat,carray)
else:
print("superposition...not implemented")
return qstat
else:
print("other gates not yet implemented")
return qstat
qubits = 2
qstat = {1:[0,1],2:[0,1]}
done = "n"
singates = {"target":target}
x=1
while x <= qubits:
while done == "n":
print("this is qubit #",x)
fstgat = "target"
print("first gate is target")
if fstgat in singates:
#checks if there is an error from mem1 being undefined (control/target out of order)
while True:
try:
qstat[x]=singates[fstgat](qstat[x])
break
except NameError:
print("switching qubits - we'll come back to this one")
#error here -> keeps saying "which gate is this target qubit for"
done = "y"
done = input("Done with your qubit? y or n: ")
else:
print("sorry, that functionality is not yet implemented, try custom gate")
done ="y"
x+=1
done = "n"
print("result for qubit",1,qstat[0])
print("result for qubit",2,qstat[1])
代码减少了,但它意味着模拟理想的量子计算机。 “qstat”是每个量子位的状态字典。它可能不需要是字典,但它在实际程序中的方式很好,所以我保留它。无论如何,“qubits”是系统中的量子位数,通常可以是用户输入的任何整数。函数“target”是cNOT门中的目标量子位。代码中出现“try ... except”部分的原因是因为有时用户会在“控制”之前输入“目标”,因为需要检查控制量子位以确定如何处理目标量子位,输出一个NameError,所以我把它设置为在我正在编码的列表中记录该量子位,以“重新计算”该列表中的每个量子位。
“完成”是一种检查用户完成每个量子位的方法,并且由于它处于while循环中,我认为在“except”语句结束while循环后将其设置为“y”并继续下一个量子比特,但由于某种原因,它停留在函数内部 - 同一行重复一遍又一遍。如果你想退出函数,你必须键入一些乱码,因为它对应于最后一个else语句,如果typegat2不等于“cNOT”,它返回qstat(没有改变)并继续前进。很明显,由于错误或其他原因,函数没有返回任何内容。但问题就变成了,我怎样才能让它退出函数?
任何帮助将不胜感激。我很乐意回答您对代码的任何问题;我试图尽可能地减少它。
答案 0 :(得分:1)
摆脱while True:
循环,导致代码在NameError
异常发生时重复。
另外,将done
的输入移到try
块中。否则,该输入将覆盖done = "y"
块中的except
语句。
while x <= qubits:
while done == "n":
print("this is qubit #",x)
fstgat = "target"
print("first gate is target")
if fstgat in singates:
#checks if there is an error from mem1 being undefined (control/target out of order)
try:
qstat[x]=singates[fstgat](qstat[x])
done = input("Done with your qubit? y or n: ")
except NameError:
print("switching qubits - we'll come back to this one")
#error here -> keeps saying "which gate is this target qubit for"
done = "y"
else:
print("sorry, that functionality is not yet implemented, try custom gate")
done ="y"
x+=1
done = "n"