Dorothydu commited on
Commit
26c564a
·
verified ·
1 Parent(s): a5a906c

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. -QuQ--master/baseClass/Circuit.py +1063 -0
  2. -QuQ--master/baseClass/Error.py +121 -0
  3. -QuQ--master/baseClass/baseGate.py +466 -0
  4. -QuQ--master/baseClass/baseQubit.py +49 -0
  5. -QuQ--master/doc/QSI-framework.png +3 -0
  6. -QuQ--master/doc/QuanSim-FrameWork.png +3 -0
  7. -QuQ--master/doc/ibm-backend/ibmqx4-backend2017.10.25.png +3 -0
  8. -QuQ--master/doc/ibm-backend/ibmqx5-backend2017.10.25-1.png +3 -0
  9. -QuQ--master/pic/QuanSim-datatype.png +3 -0
  10. -QuQ--master/results/EXP2018-03-14-15.23.40/Logical-Level/circuit.jpg +3 -0
  11. -QuQ--master/results/EXP2018-03-14-15.23.40/chart.jpg +3 -0
  12. -QuQ--master/results/EXP2018-03-14-15.23.45/Logical-Level/circuit.jpg +3 -0
  13. -QuQ--master/results/EXP2018-03-14-15.23.45/chart.jpg +3 -0
  14. -QuQ--master/userCode/GroverN=8theory/circuit.jpg +3 -0
  15. -QuQ--master/userCode/ibmGroverN=8.tar +3 -0
  16. 10-week-algorithm-excercise-master/Week_01/141/linked_list_cycle_test.go +39 -0
  17. 10-week-algorithm-excercise-master/Week_01/206/reverse_linked_list.py +45 -0
  18. 10-week-algorithm-excercise-master/Week_01/206/reverse_linked_list_test.go +26 -0
  19. 10-week-algorithm-excercise-master/Week_01/21/merge_two_sorted_lists.py +24 -0
  20. 10-week-algorithm-excercise-master/Week_01/24/swap_nodes_in_pairs.go +16 -0
  21. 10-week-algorithm-excercise-master/Week_01/641/design_circular_deque_test.go +58 -0
  22. 10-week-algorithm-excercise-master/Week_01/70/climbing_stairs.go +14 -0
  23. 10-week-algorithm-excercise-master/Week_01/84/largest_rectangle_in_histogram.go +24 -0
  24. 10-week-algorithm-excercise-master/Week_01/84/largest_rectangle_in_histogram2.go +32 -0
  25. 10-week-algorithm-excercise-master/Week_01/88/merge_sorted_array2.go +20 -0
  26. 10-week-algorithm-excercise-master/Week_01/88/merge_sorted_array2.py +22 -0
  27. 10-week-algorithm-excercise-master/Week_02/144/binary_tree_preorder_traversal.go +22 -0
  28. 10-week-algorithm-excercise-master/Week_02/144/binary_tree_preorder_traversal2.py +40 -0
  29. 10-week-algorithm-excercise-master/Week_02/144/binary_tree_preorder_traversal3.go +21 -0
  30. 10-week-algorithm-excercise-master/Week_02/144/binary_tree_preorder_traversal3.py +42 -0
  31. 10-week-algorithm-excercise-master/Week_02/264/ugly_number_ii2.go +33 -0
  32. 10-week-algorithm-excercise-master/Week_02/264/ugly_number_ii2.py +30 -0
  33. 10-week-algorithm-excercise-master/Week_02/264/ugly_number_ii_test.go +18 -0
  34. 10-week-algorithm-excercise-master/Week_02/347/top_k_frequent_elements.go +49 -0
  35. 10-week-algorithm-excercise-master/Week_02/347/top_k_frequent_elements2.go +42 -0
  36. 10-week-algorithm-excercise-master/Week_02/347/top_k_frequent_elements_test.go +26 -0
  37. 10-week-algorithm-excercise-master/Week_02/429/n_ary_tree_level_order_traversal.go +26 -0
  38. 10-week-algorithm-excercise-master/Week_02/429/n_ary_tree_level_order_traversal.py +24 -0
  39. 10-week-algorithm-excercise-master/Week_02/429/n_ary_tree_level_order_traversal2.go +25 -0
  40. 10-week-algorithm-excercise-master/Week_02/49/group_anagrams.go +25 -0
  41. 10-week-algorithm-excercise-master/Week_02/49/group_anagrams.py +35 -0
  42. 10-week-algorithm-excercise-master/Week_02/49/group_anagrams_test.go +23 -0
  43. 10-week-algorithm-excercise-master/Week_02/589/n_ary_tree_preorder_traversal.go +21 -0
  44. 10-week-algorithm-excercise-master/Week_02/589/n_ary_tree_preorder_traversal.py +21 -0
  45. 10-week-algorithm-excercise-master/Week_02/589/n_ary_tree_preorder_traversal2.go +18 -0
  46. 10-week-algorithm-excercise-master/Week_02/589/n_ary_tree_preorder_traversal2.py +21 -0
  47. 10-week-algorithm-excercise-master/Week_02/590/n_ary_tree_postorder_traversal.go +21 -0
  48. 10-week-algorithm-excercise-master/Week_02/590/n_ary_tree_postorder_traversal2.go +22 -0
  49. 10-week-algorithm-excercise-master/Week_02/590/n_ary_tree_postorder_traversal2.py +21 -0
  50. 10-week-algorithm-excercise-master/Week_02/590/n_ary_tree_postorder_traversal_test.go +20 -0
-QuQ--master/baseClass/Circuit.py ADDED
@@ -0,0 +1,1063 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ import os
3
+ import psutil
4
+ sys.path.append('../tools/')
5
+ import interactCfg
6
+ import helperFunction
7
+ import datetime
8
+ import random
9
+ from Bit import Bit
10
+ from Qubit import *
11
+ from Error import *
12
+ from IBMQX import *
13
+ #from Gate import *
14
+ import numpy as np
15
+ import matplotlib.pyplot as plt
16
+ import matplotlib.patches as patches
17
+ from mpl_toolkits.axes_grid.anchored_artists import AnchoredText
18
+ import csv
19
+ import re
20
+
21
+ #the circuit.py will use this one
22
+ styleDic = {
23
+ "I":[" I ","C5"],
24
+ "X":["X","C0"],
25
+ "Y":["Y","C1"],
26
+ "Z":["Z","C1"],
27
+ "H":["H","C2"],
28
+ "S":["S","C8"],
29
+ "T":["T","C4"],
30
+ #"CNOT":["+","C0"],
31
+ "Td":["Td","C6"],
32
+ "Sd":["Sd","C7"],
33
+ "M":["M","C3"],
34
+ "qif":["qif","C3"],
35
+ "Rz":["Rz","C5"],
36
+ "Ry":["Ry","C5"],
37
+ "Rx":["Rx","C5"]
38
+ #"Toffoli":["+","C0"],
39
+ #multi-controlled gate
40
+ }
41
+
42
+
43
+ ResLocation = "../results/"
44
+
45
+ #the data-type is the elementary unit of executing and export
46
+ class Circuit:
47
+ #mark the environment: we can execute the code when there is only one circuit in the environment
48
+ currentIDList = []
49
+ instance = None
50
+
51
+ #the parameter "withOriginalData" is True, then record the componone elements of MCU
52
+ #instead of the whole gateName. And in this mode, it will figure out more detailed data
53
+ def __init__(self,withOriginalData = False,experimentName=None):
54
+ self.beginMemory = 0
55
+ self.endMemory = 0
56
+ self.beginTime = datetime.datetime.now()
57
+ self.endTime = 0
58
+ if experimentName == None:
59
+ dt = self.beginTime
60
+ experimentName = "EXP" + str(dt.date()) + '-' + str(dt.strftime('%X')).replace(':','.')
61
+ self.name = experimentName
62
+ #use this value to uniquely identify
63
+ self.ids = id(self)
64
+
65
+ folderName = ResLocation+self.name
66
+ #create a new folder to save the experiment
67
+ helperFunction.createFolder(folderName)
68
+
69
+ self.urls = folderName
70
+ #each qubit stands for a individual dimension
71
+ #see /doc/Class-relation.doc for details
72
+ self.qubitExecuteList = {}
73
+ self.qubitNum = 0
74
+ Circuit.currentIDList.append(self.ids)
75
+ Circuit.instance = self
76
+ #put all the qubit which need measurement in this list
77
+ self.measureList = []
78
+ #record the execute mode of the current instance
79
+ self.mode = interactCfg.readCfgEM()
80
+
81
+ if withOriginalData:
82
+ self.withOD = True
83
+ else:
84
+ self.withOD = False
85
+
86
+ #print information and decide whether execute IBMQX
87
+ self.ibm = False#whether execute experiments on IBM platform
88
+ self.__printPreMsg()
89
+
90
+ if self.withOD:
91
+ self.qubitNumOD = 0
92
+ self.qubitExecuteListOD = {}
93
+ #the if statement of QASM will be stored in this dict so that the statement won't be repeated
94
+ self.IFList = []
95
+ self.IFDic = {}
96
+ #update the value
97
+ self.beginMemory = psutil.Process(os.getpid()).memory_info().rss
98
+ self.beginTime = datetime.datetime.now()
99
+
100
+
101
+ #the destory function
102
+ def __del__(self):
103
+ ids = id(self)
104
+ if ids in Circuit.currentIDList:
105
+ Circuit.currentIDList.remove(id(self))
106
+ else:
107
+ return
108
+
109
+ #check the environment: whether the current circuit is equal to this instance
110
+ def checkEnvironment(self):
111
+ #if there is ErrorMsg.txt in the folder, then exit <QuQ>
112
+ #it means that there is exception in With block and we should exit the program
113
+ if os.path.exists(self.urls + "/errorMsg.txt"):
114
+ #True
115
+ sys.exit(1)
116
+
117
+ circuitNum = len(Circuit.currentIDList)
118
+ if self.qubitNum != len(self.qubitExecuteList):
119
+ return False
120
+ #there only can be one instance and the id of this instance must be equal with self.ids
121
+ if circuitNum == 1 and Circuit.currentIDList[0] == self.ids:
122
+ return True
123
+ try:
124
+ strs = "There are " + str(len(Circuit.currentIDList)) + " Circuit instance, please check your code"
125
+ raise EnvironmentError(strs)
126
+ except EnvironmentError as ee:
127
+ info = helperFunction.get_curl_info()
128
+ funName = info[0]
129
+ line = info[1]
130
+ interactCfg.writeErrorMsg(ee.value,funName,line)
131
+
132
+ #figure out the number of the auxiliary qubits and the actual qubits
133
+ def __countACandAX(self):
134
+ if self.withOD:
135
+ er = self.qubitExecuteListOD
136
+ else:
137
+ er = self.qubitExecuteList
138
+ AX = 0
139
+ AC = 0
140
+ for q in er:
141
+ if q.tag == "AX":
142
+ AX += 1
143
+ else:
144
+ AC += 1
145
+ return [AX,AC]
146
+
147
+ #if the statement is Qif or Mif, then execute the method
148
+ #"content" stands for the executive record of this qubit
149
+ #"gate" stands for the gate name
150
+ #"m" stands for the m-th record in content
151
+ #"qubits" stands for the string consisted of q.ids and "," as separator
152
+ #"code" stands for the QASM list
153
+ #if the function return False, then the gate isn't the Mif or Qif
154
+ def __generateIF(self,content,gate,m,qubits,code):
155
+ #judge whether the statement is the "if-statement"
156
+ if re.search(r'^(M\d-)+.+$',gate) != None:
157
+ #Mif or Qif
158
+
159
+ MgateList = re.findall(r'(M\d)',gate)
160
+ #construct the control guard
161
+ guard = ""
162
+ for j in range(0,len(MgateList)):
163
+ guard += "M[" + qubits[j] + "]=" + MgateList[j].split("M")[1]
164
+ if j != len(MgateList)-1:
165
+ guard += " && "
166
+
167
+ #judge whether the qubit is the measured qubit
168
+ #or qubits are required to act quantum gate
169
+ tag = False
170
+ for k in range(0,m):
171
+ if re.search(r'^M \d+$',content[k]) != None:
172
+ #the measured qubit
173
+ if guard in self.IFList:
174
+ pass
175
+ else:
176
+ #construct the if-statement
177
+ ifStr = "if("
178
+ for j in range(0,len(MgateList)):
179
+ tmpStr = "c[" + qubits[j] + "]=="
180
+ tmpStr += MgateList[j][1]
181
+ if j != len(MgateList)-1:
182
+ tmpStr += " && "
183
+ ifStr += tmpStr
184
+ ifStr += ")"
185
+ code.append(ifStr)
186
+ self.IFList.append(guard)
187
+ tag = True
188
+ break
189
+
190
+ #qubits are required to act quantum gate
191
+ if tag == False:
192
+ #store the statement in self.IFStatement and write them to QASM.txt in the end of the method
193
+ statement = ""
194
+ gl = gate.split("-")
195
+ if len(gl) != len(qubits):
196
+ try:
197
+ raise CodeError("The gate number isn't same with the qubit number!")
198
+ except CodeError as ce:
199
+ info = helperFunction.get_curl_info()
200
+ funName = info[0]
201
+ line = info[1]
202
+ interactCfg.writeErrorMsg(ce,funName,line)
203
+
204
+ ifGate = ""
205
+ ifQ = ""
206
+ for i in range(0,len(gl)):
207
+ if re.search(r'^M\d$',gl[i]) != None:
208
+ pass
209
+ else:
210
+ ifGate += gl[i]
211
+ ifQ += "q["+qubits[i]+"]"
212
+ if i != len(gl)-1:
213
+ ifQ += ","
214
+ if re.search(r'^c\dX\d$',ifGate) != None:
215
+ ifGate = "CNOT"
216
+ else:
217
+ ifGate = ifGate[0:len(ifGate)-1]
218
+
219
+ #store the statement
220
+ reStr = ifGate + " " + ifQ + ";"
221
+ if guard not in self.IFDic:
222
+ self.IFDic[guard] = []
223
+ if reStr in self.IFDic[guard]:
224
+ pass
225
+ else:
226
+ self.IFDic[guard].append(reStr)
227
+ return True
228
+ return False
229
+
230
+ #write the statement to QASM.txt
231
+ #"statement" stands for the QASM list
232
+ #and append the if statement according to self.IFDic and self.IFList
233
+ def __printCode(self,fileName,statement):
234
+ #append content in the original txt file
235
+ try:
236
+ code = open(fileName,"w")
237
+ for c in statement:
238
+ codeStr = ""
239
+ #the if statement
240
+ if re.search(r'if(.+)',c) != None:
241
+ #the format of c is "if(c[0]==1 && c[1]==0)"
242
+ codeStr = c + "{\n"
243
+ guard = re.findall(r'\((.*?)\)',c)[0]
244
+ #the format of key is "M[0]=1 && M[1]=0"
245
+ guard = guard.replace("c","M").replace("==","=")
246
+ for s in self.IFDic[guard]:
247
+ #append the indentation
248
+ codeStr += " "+ s + "\n"
249
+ codeStr += "}\n"
250
+ else:
251
+ codeStr = c
252
+ code.write(codeStr)
253
+ code.close()
254
+ except IOError:
255
+ info = helperFunction.get_curl_info()
256
+ interactCfg.writeErrorMsg("Can't write the QASM code to " + fileName + "!",info[0],info[1])
257
+
258
+ #restore the value of the IFDic and IFList
259
+ self.IFList = []
260
+ self.IFDic = {}
261
+
262
+
263
+ #draw the circuit according to the qubitExecuteList
264
+ #the parameter "typeQN" is a list [the number of AX qubits, the number of AC qubits]
265
+ def __exportCircuit(self,er,typeQN,fileLocation):
266
+ global alertMsg
267
+ if self.checkEnvironment():
268
+ if alertMsg:
269
+ print("begin drawing the circuit...")
270
+ #set the canvas
271
+ Fig = plt.figure('circuit',figsize=(12,6))
272
+ #set the axis off
273
+ plt.axis('off')
274
+ #devide the canvas into 1row 1col, and our pic will be draw on the first place(from up to down, from left to right)
275
+ Ax = Fig.add_subplot(111)
276
+ qubitNum = typeQN[1]
277
+ ############################draw the line according to self.qubitNum###########################
278
+ partition = 100 // qubitNum
279
+ for i in range(0,qubitNum):
280
+ X = range(0,100)
281
+ Y = [i*partition] * 100
282
+ Ax.plot(X,Y,'#000000')
283
+ ############################the line has been completed########################################
284
+
285
+ ############################draw the gate according to self.qubitExecuteList###################
286
+ j = 0
287
+ maxLength = 0
288
+ q_keys = []
289
+ for qe in er.keys():
290
+ #the auxiliary qubit won't be in the q_keys
291
+ if qe.tag == "AX":
292
+ #the qubit is the auxiliary qubit
293
+ pass
294
+ else:
295
+ maxLength = max(maxLength,len(er[qe]))
296
+ q_keys.append(qe)
297
+ quickSortQubit(q_keys,0,len(q_keys)-1)
298
+ for q in q_keys:
299
+ if q.tag == "AX":
300
+ #the qubit is an auxiliary qubit and need NOT be drawed
301
+ continue
302
+ if maxLength < 20:
303
+ factor = 1
304
+ else:
305
+ factor = maxLength / 20
306
+ #label the ids
307
+ label = 'Q' + str(q.ids)
308
+ Ax.annotate(label,xy=(0, j*partition), xytext=(-4, j*partition-0.5),size=12,)
309
+ #draw the gate
310
+ executeList = er[q]
311
+ x_position = 4 / factor
312
+ for item in executeList:
313
+ gate = item.split(" ")[0]
314
+ style = "square"
315
+ #the gate 'NULL' was stored to the list is to occupy the postion so that we can draw the circuit easily
316
+ if gate == 'NULL':
317
+ x_position += 5 / factor
318
+ continue
319
+
320
+ #remove the parameter of the gate
321
+ if re.search(r'^R\w{1}\(.+\)$',gate) != None:
322
+ gate = gate.split("(")[0]
323
+
324
+ if gate in styleDic:
325
+ gateName = styleDic[gate][0]
326
+ gateColor = styleDic[gate][1]
327
+ ann = Ax.annotate(gateName,
328
+ xy=(1, 20), xycoords='data',
329
+ xytext=(x_position, j*partition), textcoords='data',color='w',
330
+ size=12/factor, va="center", ha="center",
331
+ bbox=dict(boxstyle=style, fc=gateColor,pad=0.3,ec=gateColor),
332
+ )
333
+ #it means that the gate is a MCU
334
+ else:
335
+ if gate[-1] == '0' or gate[-1] == '1':
336
+ #the gate is the Mif or Qif
337
+ gate = gate[0:len(gate)-1]
338
+ if gate == "Toffoli":
339
+ gate = "c1-c1-X"
340
+ if gate == "CNOT":
341
+ gate = "c1-X"
342
+ singleGateList = gate.split("-")
343
+ U = singleGateList[-1]
344
+
345
+ #remove the parameter of the gate
346
+ if re.search(r'^R\w{1}\(.+\)$',U) != None:
347
+ U = U.split("(")[0]
348
+
349
+ try:
350
+ if U == "X":
351
+ if re.search(r'M\d',gate) != None and singleGateList[len(singleGateList)-2] != "c1":
352
+ gateName = styleDic[U][0]
353
+ else:
354
+ gateName = "+"
355
+ else:
356
+ gateName = styleDic[U][0]
357
+ gateColor = styleDic[U][1]
358
+ except KeyError as ke:
359
+ info = helperFunction.get_curl_info()
360
+ funName = info[0]
361
+ line = info[1]
362
+ interactCfg.writeErrorMsg("Key: " + str(ke) + " is not in Dict:styleDic!",funName,line)
363
+ #wheter the current qubit is the control-qubit
364
+ qubitStrList = item.split(" ")[1].split(",")
365
+ targetQubit = qubitStrList[len(qubitStrList) - 1]
366
+ controlQubit = qubitStrList[0:len(qubitStrList)-1]
367
+ #the index of the target qubit
368
+ indexOfTarget = 0
369
+ #get the index of the target qubit
370
+ for tmp in q_keys:
371
+ if str(tmp.ids) != targetQubit:
372
+ indexOfTarget += 1
373
+ else:
374
+ break
375
+
376
+ #draw a circle in the control qubit
377
+ if str(q.ids) in controlQubit:
378
+ #print(indexOfTarget)
379
+ smaller = min(indexOfTarget,j)
380
+ bigger = max(indexOfTarget,j)
381
+ x1 = [x_position] * (bigger * partition - smaller * partition)
382
+ y1 = range(smaller * partition,bigger * partition)
383
+
384
+ #print(gate)
385
+ #draw the control-line
386
+
387
+ #if the gate is Mif or Qif
388
+ if re.search(r'^(M\d-)+.+$',gate) != None:
389
+ #judge whether the gate is Mif-CNOT or Qif-CNOT
390
+ if re.search(r'(c\d-){1}',gate) != None and str(q.ids) == controlQubit[-1]:
391
+ #the gate is CNOT then judge whether the qubit is the penult element
392
+ Ax.plot(x1,y1,gateColor)
393
+ else:
394
+ #gateColor = "black"
395
+ Ax.plot(x1,y1,gateColor,linestyle = ":")
396
+ else:
397
+ Ax.plot(x1,y1,gateColor)
398
+
399
+ indexOfCurrentQubit = controlQubit.index(str(q.ids))
400
+ #print(type(singleGateList[indexOfCurrentQubit][1:len(singleGateList[indexOfCurrentQubit])]))
401
+ if singleGateList[indexOfCurrentQubit][1:len(singleGateList[indexOfCurrentQubit])] == '0':
402
+ #the color of the inside
403
+ fc = "White"
404
+
405
+ else:
406
+ fc = gateColor
407
+ #the color of the frame
408
+ ec = gateColor
409
+ ann = Ax.annotate("1",
410
+ xy=(1, 20), xycoords='data',color=fc,
411
+ xytext=(x_position, j*partition), textcoords='data',
412
+ size=6/factor, va="center", ha="center",
413
+ bbox=dict(boxstyle="circle", fc=fc,pad=0.3,ec=ec),
414
+ )
415
+ #don't draw the CX
416
+ else:
417
+ if gateName == "+":
418
+ style = "circle"
419
+ ann = Ax.annotate(gateName,
420
+ xy=(1, 20), xycoords='data',
421
+ xytext=(x_position, j*partition), textcoords='data',color='w',
422
+ size=12/factor, va="center", ha="center",
423
+ bbox=dict(boxstyle=style, fc=gateColor,pad=0.3,ec=gateColor),
424
+ )
425
+ x_position += 5/factor
426
+
427
+ j += 1
428
+ ############################the gate has completed########################################
429
+ #plt.show()
430
+ #save the circuit
431
+ fileName = fileLocation + "circuit.jpg"
432
+ Fig.savefig(fileName)
433
+ #print("the circuit has been stored in " + self.urls.split("..")[1] + "/circuit.jpg")
434
+ if alertMsg:
435
+ print("the circuit has been drawn!\n")
436
+ return True
437
+ else:
438
+ info = helperFunction.get_curl_info()
439
+ funName = info[0]
440
+ line = info[1]
441
+ interactCfg.writeErrorMsg("the circuit instance is wrong, please check your code",funName,line)
442
+
443
+ #translate the code of the current circuit to QASM, so that they can be executed on IBMQX
444
+ def __QASM(self,er,fileLocation):
445
+ global alertMsg
446
+ if alertMsg:
447
+ print("begin export the QASM code of the circuit...")
448
+ if self.checkEnvironment():
449
+ self.IFList = []
450
+ self.IFDic = {}
451
+ qubitNum = len(er.keys())
452
+ fileName = fileLocation + "QASM.txt"
453
+ code = []
454
+ #get the ids of the qubit
455
+ qubitList = []
456
+ for q in er.keys():
457
+ qubitList.append(q)
458
+ #get the max length of the circuit depth
459
+ maxGate = 0
460
+ for i in range(0,qubitNum):
461
+ if maxGate < len(er[qubitList[i]]):
462
+ maxGate = len(er[qubitList[i]])
463
+ for m in range(0,maxGate):
464
+ for n in range(0,qubitNum):
465
+ content = er[qubitList[n]]
466
+ #print(content)
467
+ length = len(content)
468
+ #if there is no element to be draw, skip the loop
469
+ if m > length-1:
470
+ continue
471
+ item = content[m]
472
+
473
+ qubits = item.split(" ")[1].split(",")
474
+ gate = item.split(" ")[0]
475
+ if gate == 'NULL':
476
+ continue
477
+
478
+ if self.__generateIF(content,gate,m,qubits,code):
479
+ continue
480
+ else:
481
+ pass
482
+
483
+ #transform the format of the special case
484
+ if gate == "Toffoli":
485
+ gate = "c1-c1-X"
486
+ elif gate == "CNOT":
487
+ gate = "c1-X"
488
+ else:
489
+ pass
490
+
491
+ #if the gate is MCU and the current qubit is the target, that is ,
492
+ #the current qubit isn't in the first postion, then don't export the gate
493
+ if re.search(r'^(c\d-)+.+$',gate) != None and str(qubitList[n].ids) != qubits[0]:
494
+ continue
495
+
496
+ #restore the format of the special case
497
+ if gate == "c1-c1-X":
498
+ gate = "Toffoli"
499
+ elif gate == "c1-X":
500
+ gate = "CNOT"
501
+ else:
502
+ pass
503
+
504
+ #print the line of QASM code to QASM.txt
505
+ tmpCode = gate + " "
506
+ if gate == "M":
507
+ if len(qubits) != 1:
508
+ try:
509
+ raise CodeError("Can't measure more than one qubit simultaneously")
510
+ except CodeError as ce:
511
+ info = helperFunction.get_curl_info()
512
+ funName = info[0]
513
+ line = info[1]
514
+ interactCfg.writeErrorMsg(ce,funName,line)
515
+ tmpCode += "q[" + qubits[0] + "] -> c[" + qubits[0] +"];"
516
+ tmpCode += "\n"
517
+ code.append(tmpCode)
518
+ continue
519
+ for i in range(0,len(qubits)):
520
+ tmpCode += "q[" + qubits[i] + "]"
521
+ if i != len(qubits)-1:
522
+ tmpCode += ","
523
+ tmpCode += ";"
524
+ tmpCode += "\n"
525
+ code.append(tmpCode)
526
+ #print("the code has been stored in " + self.urls.split("..")[1] + "/qasm.txt")
527
+ if alertMsg:
528
+ print("the QASM code has been exported!\n")
529
+ #write the Mif code or Qif code to QASM.txt
530
+ self.__printCode(fileName,code)
531
+
532
+ return True
533
+ else:
534
+ try:
535
+ raise EnvironmentError()
536
+ except EnvironmentError as ee:
537
+ info = helperFunction.get_curl_info()
538
+ funName = info[0]
539
+ line = info[1]
540
+ interactCfg.writeErrorMsg(ee,funName,line)
541
+
542
+ #export the result of the measurement to charts
543
+ def __exportChart(self,result:list,prob:list,title:str):
544
+ print("begin exporting the result of measurements to charts...")
545
+ if self.checkEnvironment():
546
+ number = len(result)
547
+ #the dimen of the result must be same with the prob
548
+ if number != len(prob):
549
+ info = helperFunction.get_curl_info()
550
+ funName = info[0]
551
+ line = info[1]
552
+ interactCfg.writeErrorMsg("the dimension of the measurement result is not equal, please check your code",funName,line)
553
+ ###################################drawing the charts###################################
554
+ #set the canvas
555
+ Fig = plt.figure('chart',figsize=(12,12))
556
+ #plt.title("11")
557
+ #there are two sub-pictures in this picture
558
+ Ax = Fig.add_subplot(111)
559
+ Ax.set_title(title+ ':bar chart')
560
+ plt.grid(True)
561
+ #set the bar width
562
+ bar_width = 0.5
563
+ #set the position of the elements in x-axis
564
+ xticks = []
565
+ for i in range(0,number):
566
+ xticks.append(i + bar_width/2)
567
+ colors = []
568
+ #draw the line-chart
569
+ bars = Ax.bar(xticks, prob, width=bar_width, edgecolor='none')
570
+ Ax.set_ylabel('Prob')
571
+ Ax.set_xlabel('State')
572
+ #set the position of the x-label
573
+ Ax.set_xticks(xticks)
574
+ Ax.set_xticklabels(result)
575
+ #set the range of X-axis and y-axis
576
+ Ax.set_xlim([bar_width/2-0.5, number-bar_width/2])
577
+ Ax.set_ylim([0, 1])
578
+ #set the color to bar
579
+ for bar, color in zip(bars, colors):
580
+ bar.set_color(color)
581
+ #write the probability on the top of each bar of the bat chart
582
+ for item in range(0,len(xticks)):
583
+ x_position = xticks[item]
584
+ y_position = prob[item]
585
+ if y_position < 0.1:
586
+ yPosition = y_position + 0.01
587
+ else:
588
+ yPosition = y_position - 0.03
589
+ plt.text(x_position,yPosition,'{:.3f}'.format(y_position),ha='center',va='bottom')
590
+ #save the picture
591
+ #plt.show()
592
+ Fig.savefig(self.urls + "/chart.jpg")
593
+ #print("the circuit has been stored in " + self.urls.split("..")[1] + "/chart.jpg")
594
+ print("the chart of the circuit has been exported!\n")
595
+ return True
596
+ else:
597
+ info = helperFunction.get_curl_info()
598
+ funName = info[0]
599
+ line = info[1]
600
+ interactCfg.writeErrorMsg("the instance is wrong, please check your code!",funName,line)
601
+
602
+ #the aim of the function is to order the idList and get the right state according to the order
603
+ #of the ids
604
+ def __orderTheId(self,idList:list,order:list):
605
+ for i in range(1,len(idList)):
606
+ tmp = i-1
607
+ while tmp >=0:
608
+ if idList[tmp] > idList[i]:
609
+ idList[i],idList[tmp] = idList[tmp],idList[i]
610
+ order[i],order[tmp] = order[tmp],order[i]
611
+ i = tmp
612
+ tmp -= 1
613
+ return order
614
+
615
+ #execute measurement on the qubits
616
+ def execute(self,executeTimes:int):
617
+ #print(self.qubitExecuteList)
618
+ if self.checkEnvironment():
619
+ probList = []
620
+ stateList = []
621
+ qubitList = self.measureList.copy()
622
+ hasMeasure = []
623
+ #record the order of the qubit
624
+ idList = []
625
+ gateNum = self.__countGate()
626
+ totalQubitNum = self.qubitNum
627
+ executeRecord = self.qubitExecuteList.copy()
628
+ if self.withOD:
629
+ executeRecordOD = self.qubitExecuteListOD.copy()
630
+
631
+ #figure out the AC qubits number and the AX qubits number
632
+ typeQN = self.__countACandAX()
633
+
634
+ print("QuanSim is measuring the qubit, please wait for a while...")
635
+ #execute the measurement of the qubits
636
+ for qubit in qubitList:
637
+ if qubit in hasMeasure:
638
+ continue
639
+ hasMeasure.append(qubit)
640
+ #judge whether act qif on this qubit; if so, pass this loop and continue the next one.
641
+ hasQIF = False
642
+ if hasQIF:
643
+ continue
644
+ qs = qubit.entanglement
645
+ #the current qubit is not in entanglement
646
+ if qs == None:
647
+ result = qubit.decideProb()
648
+ #the result is two-dimen, result[0] is the list of probablity, and result[1] is the corresponding state
649
+ probList.append(result[0])
650
+ stateList.append(result[1])
651
+ idList.append(qubit.ids)
652
+ self.__removeQubit([qubit])
653
+ qubit.delete()
654
+ continue
655
+ #the current qubit is in entanglement
656
+ #find the other qubit ,which is also in qs.qubitList and self.measureList
657
+ qubitGroup = []
658
+ for item in qs.qubitList:
659
+ if item in qubitList:
660
+ #item will be measured with the current qubit simultaneously
661
+ #so delete the element from the list to avoid repeating measurement
662
+ #qubitList.remove(item)
663
+ if item not in hasMeasure:
664
+ hasMeasure.append(item)
665
+ hasQIF = False
666
+ #print(executeRecord[item])
667
+ if hasQIF:
668
+ pass
669
+ else:
670
+ #print(executeRecord[item])
671
+ qubitGroup.append(item)
672
+ idList.append(item.ids)
673
+ result = qubit.decideProb(qubitGroup)
674
+ #delete the measured qubit from its entangle state
675
+ self.__removeQubit(qubitGroup)
676
+ qs.deleteItem(qubitGroup)
677
+ #there is no element in qs.qubitList
678
+ if len(qs.qubitList) == 0:
679
+ del qs
680
+ #there is only one element in qs.qubitList, then there is no need to keep qs
681
+ elif len(qs.qubitList) == 1:
682
+ qs.qubitList[0].entanglement = None
683
+ del qs
684
+ else:
685
+ pass
686
+
687
+ probList.append(result[0])
688
+ stateList.append(result[1])
689
+ #use the prbList to compute the end prob
690
+ #and the state to compute the end state
691
+ #e.g., prob = [0.5,0.5],state = ['11','00']
692
+ #the state is 0.7|11> + 0.7|00>
693
+ if len(probList) == 0 and len(stateList) == 0:
694
+ #get the end time of the circuit
695
+ self.endTime = datetime.datetime.now()
696
+ self.endMemory = psutil.Process(os.getpid()).memory_info().rss
697
+ #there is no qubit has been measured
698
+ return False
699
+ #print(stateList)
700
+ prob = probList[0]
701
+ state = stateList[0]
702
+ caseNum = 2 ** len(probList)
703
+ for i in range(1,len(probList)):
704
+ tmpProb = []
705
+ tmpState = []
706
+ for j in range(0,len(prob)):
707
+ for k in range(0,len(probList[i])):
708
+ tmpProb.append(prob[j] * probList[i][k])
709
+ tmpState.append(state[j] + stateList[i][k])
710
+ prob = tmpProb
711
+ state = tmpState
712
+
713
+ #delete the zero probility and it corresponding state, and get the result
714
+ probResult = []
715
+ stateResult = []
716
+ orderList = [i for i in range(0,len(idList))]
717
+ order = self.__orderTheId(idList,orderList)
718
+ for index in range(0,len(prob)):
719
+ #if the prob is in [-0.00001,0.00001], then we regard it as 0
720
+ if prob[index] > -0.00001 and prob[index] < 0.00001 :
721
+ continue
722
+ #set the order of qubits by ASC
723
+ newStateStr = ""
724
+ for o in order:
725
+ newStateStr += state[index][int(o)]
726
+ probResult.append(prob[index])
727
+ stateResult.append(newStateStr)
728
+
729
+ #get the actual measure results according to the probResult
730
+ timesList = self.__randomM(executeTimes,probResult)
731
+ endProbResult = []
732
+ for p in range(0,len(probResult)):
733
+ endProbResult.append(timesList[p] / executeTimes)
734
+
735
+ #get the end time of the circuit
736
+ self.endTime = datetime.datetime.now()
737
+ self.endMemory = psutil.Process(os.getpid()).memory_info().rss
738
+ #get the end sequence of the ids of the qubit
739
+ title = ""
740
+ for qid in idList:
741
+ title += "q"
742
+ title += str(qid)
743
+
744
+ self.__printExecuteMsg(stateResult,endProbResult,gateNum,typeQN)
745
+ ############################exporting############################
746
+ self.__exportChart(stateResult,endProbResult,title)
747
+ self.__exportOriData(stateResult,timesList)
748
+ ############################exporting############################
749
+
750
+ ############################get the QASM and circuit######################################
751
+ global alertMsg
752
+ #use this global parameter to guarantee the alert message of getting
753
+ #QASM.txt and circuit.jpg will be printed for only once
754
+ alertMsg = True
755
+ #all the whole gate information are stored in "expName/Logical-Level/"
756
+ fileLocation = self.urls+"/Logical-Level/"
757
+ #create the folder
758
+ helperFunction.createFolder(fileLocation)
759
+
760
+ self.__exportCircuit(executeRecord,typeQN,fileLocation)
761
+ self.__QASM(executeRecord,fileLocation)
762
+ alertMsg = False
763
+
764
+ #if user want to get the original data, then call the following methods
765
+ if self.withOD:
766
+ #in this case, we should give the folder name of the QASM.txt and circuit.jpg
767
+ #all the actually executive information are stored in "expName/Physical-Level/"
768
+ fileLocation = self.urls+"/Physical-Level/"
769
+ #create the folder
770
+ helperFunction.createFolder(fileLocation)
771
+
772
+ #self.__exportCircuit(executeRecordOD,typeQN,fileLocation)
773
+ self.__QASM(executeRecordOD,fileLocation)
774
+ ############################get the QASM and circuit######################################
775
+ if self.ibm:
776
+ ibm = IBMQX()
777
+ # ibm.test()
778
+ ibm.executeQASM()
779
+ #call the destory function to clean the current instance
780
+ self.__del__()
781
+ else:
782
+ info = helperFunction.get_curl_info()
783
+ funName = info[0]
784
+ line = info[1]
785
+ interactCfg.writeErrorMsg("The instance is wrong, please check your code!",funName,line)
786
+
787
+
788
+ #remove qubitList from this instance; only the qubit has been measured, it can be removed from this instance
789
+ def __removeQubit(self,ql:list):
790
+ for q in ql:
791
+ try:
792
+ if q in self.qubitExecuteList:
793
+ self.qubitNum -= 1
794
+ del self.qubitExecuteList[q]
795
+ self.measureList.remove(q)
796
+ except KeyError:
797
+ info = helperFunction.get_curl_info()
798
+ funName = info[0]
799
+ line = info[1]
800
+ interactCfg.writeErrorMsg("KeyError: Q"+ str(q.ids) + " is not in this Circuit instance!",funName,line)
801
+
802
+ #split the unit interval into len(probList) parts, and the length of iTH interval is probList[i]
803
+ #product random number for executeTimes, then count the times of number in each interval
804
+ def __randomM(self,executeTimes,probList):
805
+ timesList = [0] * len(probList)
806
+ #product the prob interval
807
+ interval = []
808
+ sums = 0
809
+ for index in range(0,len(probList)):
810
+ try:
811
+ if index == 0:
812
+ interval.append([0,probList[0]])
813
+ else:
814
+ interval.append([sums,sums+probList[index]])
815
+ sums += probList[index]
816
+ except KeyError as ke:
817
+ info = helperFunction.get_curl_info()
818
+ funName = info[0]
819
+ line = info[1]
820
+ interactCfg.writeErrorMsg("key " + str(ke) + " doesn't exist!",funName,line)
821
+ #the error rate is lower then 0.001
822
+ if abs(1 - sums) > 0.001:
823
+ try:
824
+ raise NotNormal()
825
+ except NotNormal as nn:
826
+ info = helperFunction.get_curl_info()
827
+ funName = info[0]
828
+ line = info[1]
829
+ interactCfg.writeErrorMsg(nn,funName,line)
830
+ #product random number for executeTimes
831
+ for i in range(0,executeTimes):
832
+ #judge the number in which interval
833
+ randomNumber = random.uniform(0,1)
834
+ #the demin of timesList and interval must be same
835
+ for j in range(0,len(interval)):
836
+ if randomNumber >= interval[j][0] and randomNumber < interval[j][1]:
837
+ timesList[j] = timesList[j] + 1
838
+ return timesList
839
+
840
+ #count the numbers of the gate
841
+ def __countGate(self):
842
+ #the measured qubits of the circuit
843
+ Measure = self.measureList.copy()
844
+
845
+ #count the gate number of the circuit
846
+ Single = 0 #stands for the single-qubit gate without compiled
847
+ Multi = 0.0 #stands for the multi-qubit gate without compiled, such as c1-c1-c1-c1-X
848
+
849
+ #only if circuit.withOD == True, then compute the following two parameter
850
+ SingleOD = 0 #stands for the single gate after compiled
851
+ DoubleOD = 0 #stands for the CNOT gate after compiled
852
+
853
+ try:
854
+ from baseGate import allowGate
855
+ except ImportError:
856
+ info = helperFunction.get_curl_info()
857
+ funName = info[0]
858
+ line = info[1]
859
+ interactCfg.writeErrorMsg("Can't import the Dict: allowGate in baseGate.py!",funName,line)
860
+ for key in self.qubitExecuteList:
861
+ for operator in self.qubitExecuteList[key]:
862
+ gate = operator.split(" ")[0]
863
+ #the gate NULL is to occupy the position
864
+ if gate == "NULL" or gate == "M":
865
+ continue
866
+ #the format of the gate is M1-M0-X...
867
+ if re.search(r'^(M\d-)+.+$',gate) != None:
868
+ if gate[-1] == "0":
869
+ #the gate isn't executed
870
+ continue
871
+ else:
872
+ if "CNOT" in gate:
873
+ Multi += 1
874
+ else:
875
+ Single += 1
876
+ #the format of the gate is c1-c0-X...
877
+ if re.search(r'^(c\d-)+.+$',gate) != None:
878
+ #if the gate is c1-c1-X, then actually we count the gate for 3 times
879
+ n = len(re.findall("-",gate)) + 1
880
+ Multi += 1/n
881
+ else:
882
+ Single += 1
883
+ if self.withOD:
884
+ for key in self.qubitExecuteListOD:
885
+ for operator in self.qubitExecuteListOD[key]:
886
+ gate = operator.split(" ")[0]
887
+ #the format of the gate is M1-M0-X...
888
+ if re.search(r'^(M\d-)+.+$',gate) != None:
889
+ if gate[-1] == "0":
890
+ #the gate isn't executed
891
+ continue
892
+ else:
893
+ if "CNOT" in gate:
894
+ DoubleOD += 1
895
+ else:
896
+ SingleOD += 1
897
+ continue
898
+ #the gate NULL is to occupy the position
899
+ if gate == "NULL" or gate == "M":
900
+ continue
901
+ elif gate == "CNOT":
902
+ DoubleOD += 1
903
+ elif gate in allowGate or re.search(r'^R\w{1}\(.+\)$',gate) != None:
904
+ SingleOD += 1
905
+ else:
906
+ try:
907
+ raise GateNameError("Gate:" + gate +" hasn't defined in allowGate!")
908
+ except GateNameError as gne:
909
+ info = helperFunction.get_curl_info()
910
+ interactCfg.writeErrorMsg(gne,info[0],info[1])
911
+ #the number of the CNOT count twice when stored in the list, so we should divide 2
912
+ #and the number must be even number
913
+ if DoubleOD & 1 != 0:
914
+ #the number is odd
915
+ try:
916
+ raise CodeError("We count the CNOT gate twice in <QuQ>, and the number of CNOT \
917
+ must be an even number. However, we got an odd number! Please check your code!")
918
+ except CodeError as ce:
919
+ info = helperFunction.get_curl_info()
920
+ interactCfg.writeErrorMsg(ce,info[0],info[1])
921
+ DoubleOD = DoubleOD // 2
922
+ num = {'measureQubit':Measure,'single-qubit':Single,'multi-qubit':int(Multi+0.5),\
923
+ 'single-qubitOD':SingleOD,'double-qubit':DoubleOD}
924
+ return num
925
+
926
+ #print the executive message to cmd
927
+ def __printExecuteMsg(self,stateList,probList,gateNum,typeQN):
928
+ #the total execute time, the unit of the time is second
929
+ totalTime = (self.endTime - self.beginTime).total_seconds()
930
+ #the total memory, the unit of the memory is MB
931
+ totalMemory = ((self.endMemory - self.beginMemory) / 1024) / 1024
932
+ if self.mode == 'theory':
933
+ singleError = 'None'
934
+ doubleError = 'None'
935
+ elif self.mode == 'simulator':
936
+ singleError = 0
937
+ for q in gateNum['measureQubit']:
938
+ error = interactCfg.readCfgGE('single',q.ids)
939
+ singleError += error
940
+ singleError = "%.4f%%"%(singleError / float(len(gateNum['measureQubit'])) * 100)
941
+ doubleError = "%.4f%%"%(interactCfg.readCfgGE('multi') * 100)
942
+ else:
943
+ try:
944
+ raise ExecuteModeError()
945
+ except ExecuteModeError as em:
946
+ info = helperFunction.get_curl_info()
947
+ funName = info[0]
948
+ line = info[1]
949
+ interactCfg.writeErrorMsg(em,funName,line)
950
+
951
+ msg = "total qubits: "+ str(typeQN[0]+typeQN[1])
952
+ if self.withOD:
953
+ msg += " (Auxiliary: " + str(typeQN[0]) + ")"
954
+ msg += "\n"
955
+
956
+ msg += "the number of the measured qubits: "+ str(len(gateNum['measureQubit'])) + "\n"
957
+
958
+ msg += "the number of single-qubit gate: " + str(gateNum['single-qubit'])
959
+ if self.withOD:
960
+ msg += " (Actually execute " + str(gateNum['single-qubitOD']) + " Single Gates)"
961
+ msg += "\n"
962
+
963
+ msg += "the number of multi-qubit gate: " + str(gateNum['multi-qubit'])
964
+ if self.withOD:
965
+ msg += " (Actually execute " + str(gateNum['double-qubit']) + " CNOTs)"
966
+ msg += "\n"
967
+
968
+ msg += "executive Mode: " + self.mode + "\n"
969
+ msg += "single-qubit error: " + singleError + " (AVG)\n"
970
+ msg += "double-qubit error: " + doubleError + " (AVG)\n"
971
+ msg += "result: " + "\n"
972
+ for i in range(0,len(stateList)):
973
+ msg += " |" + str(stateList[i]) + ">----" + "%.2f%%"%(probList[i] * 100) + "\n"
974
+ msg += "executive time: " + str(totalTime) + "s\n"
975
+ msg += "memory: " + "{:.4f}".format(totalMemory) + "MB\n\n"
976
+ msg += " "*27
977
+ msg += "the circuit has been executed!!\n"
978
+ msg += "-"*80 + '\n'
979
+ #write the message to cmd and the file named "result.log"
980
+ print(msg)
981
+ try:
982
+ file = open(self.urls + "/result.log","a")
983
+ file.write("\n")
984
+ file.write(msg)
985
+ file.close()
986
+ except IOError as io:
987
+ info = helperFunction.get_curl_info()
988
+ funName = info[0]
989
+ line = info[1]
990
+ interactCfg.writeErrorMsg(io,funName,line)
991
+ return True
992
+
993
+ def __printPreMsg(self):
994
+ msg = "\n"
995
+ msg += "-"*80 + "\n"
996
+ msg += " "*27
997
+ msg += "begin executing the circuit...\n\n"
998
+ msg += "the experiment: " + self.name
999
+ #write the message to cmd and the file named "result.log"
1000
+ print(msg)
1001
+
1002
+ print("\r")
1003
+ self.__callIBM()
1004
+ print("\r")
1005
+
1006
+ try:
1007
+ file = open(self.urls + "/result.log","a")
1008
+ if self.ibm:
1009
+ boolStr = "True"
1010
+ else:
1011
+ boolStr = "False"
1012
+ file.write("Will the experiment be executed on IBMQX? "+ boolStr + "\n")
1013
+ file.write(msg)
1014
+ file.close()
1015
+ except IOError as io:
1016
+ info = helperFunction.get_curl_info()
1017
+ funName = info[0]
1018
+ line = info[1]
1019
+ interactCfg.writeErrorMsg(io,funName,line)
1020
+ return True
1021
+
1022
+ #export the original data of the experiment to the originalData.csv
1023
+ def __exportOriData(self,stateList:list,timesList:list):
1024
+ print("begin exporting original date to csv...")
1025
+ if len(stateList) != len(timesList):
1026
+ info = helperFunction.get_curl_info()
1027
+ funName = info[0]
1028
+ line = info[1]
1029
+ interactCfg.writeErrorMsg("there are something wrong with you code!",funName,line)
1030
+ csvFile = open(self.urls + "/originalData.csv","w")
1031
+ writer = csv.writer(csvFile)
1032
+ writer.writerow(['state', 'times'])
1033
+ data = []
1034
+ for i in range(0,len(stateList)):
1035
+ tuples = ('|' + str(stateList[i]) + '>',str(timesList[i]))
1036
+ data.append(tuples)
1037
+ writer.writerows(data)
1038
+ csvFile.close()
1039
+ #print("the csv file has been stored in " + self.urls.split("..")[1] + "/originalData.csv")
1040
+ print("the original data has been exported!\n")
1041
+ return True
1042
+
1043
+ #run the experiment on IBMQX by class: IBMQX
1044
+ def __callIBM(self):
1045
+ boolP = True
1046
+ #post the qasm code to ibm API according to the users's input:Y/N
1047
+ while boolP:
1048
+ boolP = False
1049
+ ibmBool = input("Do you want to execute your experiment on IBMQX? [Y/N]")
1050
+ if ibmBool == 'Y' or ibmBool == 'y':
1051
+ #yes
1052
+ self.ibm = True
1053
+ if self.withOD == False:
1054
+ #the Open-QASM is relied on the physical-level qasm.txt
1055
+ self.withOD = True
1056
+ elif ibmBool == 'N' or ibmBool == 'n':
1057
+ #no
1058
+ pass
1059
+ else:
1060
+ boolP = True
1061
+ print("Invalid input: Only 'Y' or 'N' is allowed!")
1062
+
1063
+
-QuQ--master/baseClass/Error.py ADDED
@@ -0,0 +1,121 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/python3
2
+ #the custom exceptions are written in this file
3
+ import sys
4
+ sys.path.append('../tools/')
5
+ from interactCfg import *
6
+ from helperFunction import *
7
+
8
+ #check the environment: whether the current circuit is equal to this instance
9
+ def checkEnvironment():
10
+ from Circuit import Circuit
11
+ circuitNum = len(Circuit.currentIDList)
12
+ #there only can be one instance and the id of this instance must be equal with self.ids
13
+ if circuitNum == 1:
14
+ if Circuit.currentIDList[0] == Circuit.instance.ids:
15
+ return Circuit.instance
16
+ try:
17
+ strs = "there are " + str(len(Circuit.currentIDList)) + " Circuit instance, please check your code"
18
+ raise EnvironmentError(strs)
19
+ except EnvironmentError as ee:
20
+ info = get_curl_info()
21
+ funName = info[0]
22
+ line = info[1]
23
+ writeErrorMsg(ee,funName,line)
24
+
25
+
26
+ class NoCloning(Exception):
27
+ def __init__(self,msg = None):
28
+ if msg == None:
29
+ self.value = ""
30
+ else:
31
+ self.value = msg
32
+ def __str__(self):
33
+ result = "Error Type: NoCloning\r\n"
34
+ result += "Error Message: " + self.value
35
+ return result
36
+
37
+ #the function named 'checkEnvironment' will cause this error
38
+ #there only can be one Circuit instance in runtime, more than one or none instance will cause this error
39
+ class EnvironmentError(Exception):
40
+ def __init__(self,msg = None):
41
+ if msg == None:
42
+ self.value = "There are zero or more than one Circuit instance!"
43
+ else:
44
+ self.value = msg
45
+ def __str__(self):
46
+ result = "Error Type: EnvironmentError\r\n"
47
+ result += "Error Message: " + self.value
48
+ return result
49
+
50
+ #there are something wrong with the code
51
+ class CodeError(Exception):
52
+ def __init__(self,msg=None):
53
+ if msg == None:
54
+ self.value = "There is something wrong with the QASM code!"
55
+ else:
56
+ self.value = msg
57
+ def __str__(self):
58
+ result = "Error Type: CodeError\r\n"
59
+ result += "Error Message: " + self.value
60
+ return result
61
+
62
+ #the gate name is not defined in this platfrom
63
+ class GateNameError(Exception):
64
+ def __init__(self,msg=None):
65
+ if msg == None:
66
+ self.value = "There is gates which have not defined in this platfrom!"
67
+ else:
68
+ self.value = msg
69
+ def __str__(self):
70
+ result = "Error Type: GateNameError\r\n"
71
+ result += "Error Message: " + self.value
72
+ return result
73
+
74
+
75
+ #calling the IBMQX api lead to error
76
+ class IBMError(Exception):
77
+ def __init__(self,msg = None):
78
+ if msg == None:
79
+ self.value = "There is something wrong when calling the API of IBMQX!"
80
+ else:
81
+ self.value = msg
82
+ def __str__(self):
83
+ result = "Error Type: IBMError\r\n"
84
+ result += "Error Message: " + self.value
85
+ return result
86
+
87
+ #the execute mode must be either theory or simulator, but we get another value
88
+ class ExecuteModeError(Exception):
89
+ def __init__(self,msg = None):
90
+ if msg == None:
91
+ self.value = "executeMode must be either 'theory' or 'simulator', but we get another mode"
92
+ else:
93
+ self.value = msg
94
+ def __str__(self):
95
+ result = "Error Type: ExecuteModeError\r\n"
96
+ result += "Error Message: " + self.value
97
+ return result
98
+
99
+ #the id of the qubit must be unique
100
+ class IDRepeatError(Exception):
101
+ def __init__(self,msg=None):
102
+ if msg == None:
103
+ self.value = "the id of the qubit has been used, please choose another id"
104
+ else:
105
+ self.value = msg
106
+ def __str__(self):
107
+ result = "Error Type: IDRepeatError\r\n"
108
+ result += "Error Message: " + self.value
109
+ return result
110
+
111
+ #the qubit or qubits is not normal
112
+ class NotNormal(Exception):
113
+ def __init__(self,msg=None):
114
+ if msg == None:
115
+ self.value = "the qubit or qubits is not normal, please normalize the measured qubit!"
116
+ else:
117
+ self.value = msg
118
+ def __str__(self):
119
+ result = "Error Type: NotNormal\r\n"
120
+ result += "Error Message: " + self.value
121
+ return result
-QuQ--master/baseClass/baseGate.py ADDED
@@ -0,0 +1,466 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/python3
2
+ import sys
3
+ import os
4
+ sys.path.append('../tools/')
5
+ from interactCfg import *
6
+ from Bit import Bit
7
+ from Qubit import *
8
+ from helperFunction import *
9
+ #from Circuit import Circuit
10
+ from Error import *
11
+ import numpy as np
12
+ import math
13
+ import cmath
14
+
15
+ #baseGate.py and Gate.py will use the DIC
16
+ allowGate = {
17
+ 'X':1,
18
+ 'Y':1,
19
+ 'Z':1,
20
+ 'CNOT':2,
21
+ 'S':1,
22
+ 'Sd':1,
23
+ 'T':1,
24
+ 'Td':1,
25
+ 'H':1,
26
+ 'I':1,
27
+ 'M':1,
28
+ 'Rz':1,
29
+ 'Ry':1,
30
+ #'Rx':1
31
+ }
32
+
33
+ class Gate:
34
+ def __init__(self,ql:list,gate:list,gateName:str):
35
+ self.gateName = gateName
36
+ self.gate = gate
37
+ if self.__checkType(ql):
38
+ self.ql = ql
39
+
40
+ #the method has two parameters:
41
+ #the former stands for whether record the gate in qubitExecuteList
42
+ #the latter stands fot the angle parameter of the gate,
43
+ #only the parameter of Rx,Ry and Rz gate isn't None
44
+ def singleOperator(self,record = True,angle = None,forceQuit = False):
45
+ q = self.ql[0]
46
+ if angle != None and self.gateName not in ["Rx","Ry","Rz"]:
47
+ try:
48
+ raise GateNameError()
49
+ except GateNameError as gne:
50
+ info = self.get_curl_info()
51
+ writeErrorMsg(gne,info[0],info[1])
52
+
53
+ circuit = self.recordSingleExecution(record,angle,forceQuit)
54
+
55
+ qs = q.entanglement
56
+ noise = Noise(self.ql)
57
+ v = noise.simNoise(self.gate)
58
+ del noise
59
+ #the qubit is in entanglement
60
+ if qs != None:
61
+ q = self.__handleQubits(v,q)
62
+ else:
63
+ result = self.__matrixCompution(v,q.getMatrix()).tolist()
64
+ q.setMatrix(result)
65
+ return q
66
+
67
+ def CNOTOperator(self,record = True,forceQuit = False):
68
+ q1 = self.ql[0]
69
+ q2 = self.ql[1]
70
+
71
+ #q1 is same with q2
72
+ try:
73
+ if id(q1) == id(q2):
74
+ raise CodeError("The control-qubit can't be same with the target-qubit of CNOT gate!")
75
+ except CodeError as ce:
76
+ info = self.get_curl_info()
77
+ funName = info[0]
78
+ line = info[1]
79
+ writeErrorMsg(ce,funName,line)
80
+
81
+ circuit = self.recordmultiExecution(record,None,forceQuit)
82
+
83
+ noise = Noise(self.ql)
84
+ v = noise.simNoise(self.gate)
85
+ del noise
86
+ q1Entangle = q1.entanglement
87
+ q2Entangle = q2.entanglement
88
+ #the twp qubits are single qubit
89
+ if q1Entangle == None and q2Entangle == None:
90
+ #construct the qubits
91
+ qs = Qubits(q1,q2)
92
+ result = self.__matrixCompution(v,qs.getMatrix()).tolist()
93
+ qs.setMatrix(result)
94
+ return qs
95
+ #the two qubits are in the same qubits
96
+ elif q1Entangle != None and q1Entangle == q2Entangle:
97
+ qs = q1Entangle
98
+ q = q2
99
+ #at least one of the two qubits are in entanglement
100
+ else:
101
+ #append q into qs
102
+ if q1Entangle == None:
103
+ qs = q2Entangle
104
+ q = q1
105
+ else:
106
+ qs = q1Entangle
107
+ if q2Entangle == None:
108
+ q = q2
109
+ else:
110
+ q = q2Entangle
111
+ #add q to qs, no matter the type of q is Qubit or Qubits
112
+ qs.addNewItem(q)
113
+ #note that the position of q1 and q2 may be different from before
114
+ q1Position = qs.getIndex(q1)
115
+ q2Position = qs.getIndex(q2)
116
+ #compute the result according to the function of CNOT
117
+ #if the control qubit aren't in |1>
118
+ if q1.getMatrix()[1] == 0:
119
+ return qs
120
+ totalQubit = len(qs.qubitList)
121
+ basicNum = 2 ** (totalQubit - q1Position - 1)
122
+ floatNum = 2 ** (totalQubit - q2Position - 1)
123
+ swapList = []
124
+
125
+ for i in range(basicNum, 2 ** totalQubit - floatNum):
126
+ #decide whether i has been in the swapList
127
+ whetherIn = False
128
+ for item in swapList:
129
+ if i in item:
130
+ whetherIn = True
131
+ break
132
+ if whetherIn == True:
133
+ continue
134
+ #we should make sure that the q1Postionth bit of 'i' is 1; if so, it means that the control bit is |1>, and
135
+ #we need to flip the target; if not, the target qubit doesn't beed to be flipped
136
+ if i & basicNum != 0:
137
+ tmpList = [i,i+floatNum]
138
+ swapList.append(tmpList)
139
+ newQSMatrix = qs.getMatrix()
140
+ for lists in swapList:
141
+ newQSMatrix[lists[0]],newQSMatrix[lists[1]] = newQSMatrix[lists[1]],newQSMatrix[lists[0]]
142
+ qs.setMatrix(newQSMatrix)
143
+ return qs
144
+
145
+ def MOperator(self,result = True):
146
+ q = self.ql[0]
147
+ #just store the M gate in circuit.qubitExecuteList,
148
+ #the measurement will actually occur when function circuit.execute is called
149
+ if q.tag == "AC":
150
+ circuit = self.recordSingleExecution()
151
+ if result == True:
152
+ #store the measurement qubit in the self.measureList
153
+ circuit.measureList.append(q)
154
+
155
+ bit = q.degenerate()
156
+ value = bit.value
157
+ newMatrix = []
158
+ if value == 0:
159
+ newMatrix = [[1],[0]]
160
+ else:
161
+ newMatrix = [[0],[1]]
162
+ q.setMatrix(newMatrix)
163
+
164
+ return bit
165
+ #return data.degenerate()
166
+
167
+ #get the info about the function name and the line number
168
+ def get_curl_info(self):
169
+ try:
170
+ raise Exception
171
+ except:
172
+ f = sys.exc_info()[2].tb_frame.f_back
173
+ return [f.f_code.co_name, f.f_lineno]
174
+
175
+ #check the number of rows and cols, the result must be n*1 or m*m, otherwise raise an error
176
+ def __checkMatrix(self,m:list):
177
+ rows = len(m)
178
+ try:
179
+ cols = len(m[0])
180
+ for i in range(0,rows):
181
+
182
+ if cols != len(m[i]):
183
+ #each row must have the same number of elements
184
+ raise ValueError("each row doesn't have the same number of elements")
185
+ if cols != 1 and cols != rows:
186
+ raise ValueError("the format of the list is wrong")
187
+ except KeyError as ke:
188
+ info = self.get_curl_info()
189
+ funName = info[0]
190
+ line = info[1]
191
+ writeErrorMsg(ke,funName,line)
192
+ except ValueError as ve:
193
+ info = self.get_curl_info()
194
+ funName = info[0]
195
+ line = info[1]
196
+ writeErrorMsg(ve,funName,line)
197
+ lists = [rows,cols]
198
+ return lists
199
+
200
+ #check the type of the input, only Qubit is allowed.
201
+ def __checkType(self,ql:list):
202
+ for q in ql:
203
+ types = type(q)
204
+ #print(types)
205
+ if types == Bit:
206
+ try:
207
+ raise TypeError
208
+ except TypeError:
209
+ info = self.get_curl_info()
210
+ funName = info[0]
211
+ line = info[1]
212
+ writeErrorMsg("Bit " + str(q.ids) + " has been meaured! You can't act any quntum gate on it!",funName,line)
213
+ if types != Qubit:
214
+ try:
215
+ raise TypeError
216
+ except TypeError:
217
+ info = self.get_curl_info()
218
+ funName = info[0]
219
+ line = info[1]
220
+ writeErrorMsg("The type of the date should be Qubit!",funName,line)
221
+ return True
222
+
223
+ #compution the matrix multiplication
224
+ def __matrixCompution(self,l1:list,l2:list):
225
+ rc1 = self.__checkMatrix(l1)
226
+ rc2 = self.__checkMatrix(l2)
227
+ if rc1 == None or rc2 == None or rc1[1] != rc2[0]:
228
+ info = self.get_curl_info()
229
+ funName = info[0]
230
+ line = info[1]
231
+ writeErrorMsg("the matrix is error",funName,line)
232
+ gate = np.matrix(l1)
233
+ qubit = np.matrix(l2)
234
+ return (gate*qubit)
235
+
236
+ #if the input of GATE is in entanglement, then call this function
237
+ def __handleQubits(self,gate:list , q:Qubit):
238
+ qs = q.entanglement
239
+ #get the index of the q in qs
240
+ position = qs.getIndex(q)
241
+ totalQubit = len(qs.qubitList)
242
+ basic = 2 ** (totalQubit - position - 1)
243
+ endResult = []
244
+ for i in range(0,2 ** totalQubit):
245
+ tmpResult = []
246
+ for n in range(0,2 ** totalQubit):
247
+ tmpResult.append([0])
248
+ amplitude = qs.getAmp()[i]
249
+ #pass the number i
250
+ if amplitude == 0.0:
251
+ endResult.append(tmpResult)
252
+ continue
253
+ #the target qubit is in |0>
254
+ if i & basic == 0:
255
+ tmpMatrix = [[1],[0]]
256
+ result = self.__matrixCompution(gate,tmpMatrix).tolist()
257
+ try:
258
+ result[0][0] = amplitude * result[0][0]
259
+ result[1][0] = amplitude * result[1][0]
260
+ except IndexError as ie:
261
+ info = self.get_curl_info()
262
+ funName = info[0]
263
+ line = info[1]
264
+ writeErrorMsg(ie,funName,line)
265
+ tmpResult[i][0] = result[0][0]
266
+ tmpResult[i + basic][0] = result[1][0]
267
+ #the target qubit is in |1>
268
+ else:
269
+ tmpMatrix = [[0],[1]]
270
+ result = self.__matrixCompution(gate,tmpMatrix).tolist()
271
+ try:
272
+ result[0][0] = amplitude * result[0][0]
273
+ result[1][0] = amplitude * result[1][0]
274
+ except IndexError as ie:
275
+ info = self.get_curl_info()
276
+ funName = info[0]
277
+ line = info[1]
278
+ writeErrorMsg(ie,funName,line)
279
+ tmpResult[i][0] = result[1][0]
280
+ tmpResult[i - basic][0] = result[0][0]
281
+ #print(newMatrix)
282
+ endResult.append(tmpResult)
283
+ sumResult = endResult[0]
284
+ for r in range(1,len(endResult)):
285
+ for x in range(0,len(endResult[r])):
286
+ sumResult[x][0] += endResult[r][x][0]
287
+ qs.setMatrix(sumResult)
288
+ return q
289
+
290
+ #record the execution
291
+ #if the environment is wrong, will cause the EnvironmentError
292
+ #if the return-value is None, then there is somrthing wrong with the Circuit instance, and the program should be end
293
+ #or the current qubit is not stored in the executeList
294
+ #1.recordSingleExecution: record single gate, i.e. X,Y..
295
+ #2.recordMultiExecution:record multi gate, i.e. CNOT..
296
+ def recordSingleExecution(self,record = True,angle = None,forceQuit = False):
297
+ #only Mif and Qif will give the forceQuit to True
298
+ #if forceQuit is true, then end this method directly
299
+ if forceQuit:
300
+ return None
301
+ c = self.__recordSE(record,None,angle)
302
+ if c.withOD:
303
+ return self.__recordSE(True,c.qubitExecuteListOD,angle)
304
+ return c
305
+
306
+ def recordmultiExecution(self,record = True,angle = None,forceQuit = False):
307
+ if forceQuit:
308
+ return None
309
+ c = self.__recordME(record,None,angle)
310
+ if c.withOD:
311
+ return self.__recordME(True,c.qubitExecuteListOD,angle)
312
+ return c
313
+
314
+ def __recordSE(self,record,executeList = None,angle = None):
315
+ q = self.ql[0]
316
+ circuit = checkEnvironment()
317
+ if record == False:
318
+ return circuit
319
+ #record the execution according to the qubit.ids
320
+ ids = q.ids
321
+
322
+ if executeList == None:
323
+ executeList = circuit.qubitExecuteList
324
+ else:
325
+ #if the parameter "executeList" isn't None
326
+ #then it means that we are recording the executive record in circuit.qubitexecutelistOD
327
+ if self.gateName not in allowGate:
328
+ return circuit
329
+ #print(self.gateName)
330
+
331
+ if angle == None:
332
+ strs = self.gateName + " " + str(ids)
333
+ else:
334
+ #change format of the parameter "angle" to multiples of "PI"
335
+ tmpAngle = ""
336
+ multiplesList = str(angle / math.pi).split(".")
337
+ if len(multiplesList[1]) > 3:
338
+ tmpAngle = multiplesList[0] + "." + multiplesList[1][0:3]
339
+ else:
340
+ tmpAngle = multiplesList[0] + "." + multiplesList[1]
341
+ angleS = tmpAngle + "*pi"
342
+ strs = self.gateName + "(" + angleS + ") " + str(ids)
343
+
344
+ try:
345
+ #a qubit can only be measured once, and once the qubit was measured, you can't act any gate on it.
346
+ if "M "+str(ids) in executeList[q]:
347
+ try:
348
+ raise ValueError
349
+ except ValueError:
350
+ info = self.get_curl_info()
351
+ funName = info[0]
352
+ line = info[1]
353
+ writeErrorMsg("Qubit: q"+ str(q.ids) + " has been measured! You can't act any gate on it!",funName,line)
354
+
355
+ executeList[q].append(strs)
356
+
357
+ except KeyError as ke:
358
+ info = self.get_curl_info()
359
+ funName = info[0]
360
+ line = info[1]
361
+ writeErrorMsg("The current qubit is not stored in the execute list, please check your code!",funName,line)
362
+ return circuit
363
+
364
+ def __recordME(self,record,executeList = None,angle = None):
365
+ circuit = checkEnvironment()
366
+ if record == False:
367
+ return circuit
368
+ if circuit != None:
369
+ if executeList == None:
370
+ executeList = circuit.qubitExecuteList
371
+ else:
372
+ #if the parameter "executeList" isn't None
373
+ #then it means that we are recording the executive record in circuit.qubitexecutelistOD
374
+ if self.gateName not in allowGate:
375
+ return circuit
376
+
377
+ #print(exeRecord)
378
+ if angle == None:
379
+ strs = self.gateName + " "
380
+ else:
381
+ #change format of the parameter "angle" to multiples of "PI"
382
+ tmpAngle = ""
383
+ multiplesList = str(angle / math.pi).split(".")
384
+ if len(multiplesList[1]) > 3:
385
+ tmpAngle = multiplesList[0] + "." + multiplesList[1][0:3]
386
+ else:
387
+ tmpAngle = multiplesList[0] + "." + multiplesList[1]
388
+ angleS = tmpAngle + "*pi"
389
+ strs = self.gateName + "(" + angleS + ") "
390
+
391
+ maxLength = 0
392
+ #make up the multi gate string
393
+ for i in range(0,len(self.ql)):
394
+ ids = self.ql[i].ids
395
+ try:
396
+ length = len(executeList[self.ql[i]])
397
+ if "M " + str(ids) in executeList[self.ql[i]]:
398
+ raise ValueError
399
+ except KeyError as ke:
400
+ info = self.get_curl_info()
401
+ funName = info[0]
402
+ line = info[1]
403
+ writeErrorMsg("Qubit: q" + str(self.ql[i].ids) + " is not stored in the execute list, please check your code!",funName,line)
404
+ except ValueError:
405
+ info = self.get_curl_info()
406
+ funName = info[0]
407
+ line = info[1]
408
+ writeErrorMsg("Qubit: q"+ str(self.ql[i].ids) + " has been measured! You can't act any gate on it!",funName,line)
409
+ if maxLength < length:
410
+ maxLength = length
411
+ strs += str(ids)
412
+ if i != len(self.ql) - 1:
413
+ strs += ","
414
+ #add the multi gate string to the execution of each qubit;
415
+ #and add NULL to the shorter execution to occupy the position so that we can draw the circuit easily
416
+ for item in self.ql:
417
+ while len(executeList[item]) < maxLength:
418
+ tmpStr = "NULL " + str(item.ids)
419
+ executeList[item].append(tmpStr)
420
+ executeList[item].append(strs)
421
+ return circuit
422
+
423
+ #add noise to the gate; the noise value is read from errorRate.cfg
424
+ #attention, only the execute mode is 'simulator', then the function is useful
425
+ class Noise:
426
+ def __init__(self,qList:list):
427
+ circuit = checkEnvironment()
428
+ self.error = 0.0
429
+ self.qList = qList
430
+ if circuit.mode == "theory":
431
+ pass
432
+ elif circuit.mode == "simulator":
433
+ qNum = len(qList)
434
+ if qNum == 1:
435
+ self.error = interactCfg.readCfgGE("single",qList[0].ids)
436
+ elif qNum == 2:
437
+ self.error = interactCfg.readCfgGE("multi")
438
+ else:
439
+ info = self.get_curl_info()
440
+ funName = info[0]
441
+ line = info[1]
442
+ writeErrorMsg("There are only single-qubit or double-qubit gate error!",funName,line)
443
+ else:
444
+ try:
445
+ raise ExecuteModeError()
446
+ except ExecuteModeError as em:
447
+ info = self.get_curl_info()
448
+ funName = info[0]
449
+ line = info[1]
450
+ writeErrorMsg(em,funName,line)
451
+
452
+ def simNoise(self,gate:list):
453
+ if self.error == 0.0:
454
+ return gate
455
+ else:
456
+ for i in range(0,len(gate)):
457
+ for j in range(0,len(gate[0])):
458
+ if gate[i][j] == 0:
459
+ gate[i][j] = 1 - (1.0 * (1 - self.error))
460
+ else:
461
+ gate[i][j] = gate[i][j] * (1 - self.error)
462
+ return gate
463
+
464
+
465
+
466
+
-QuQ--master/baseClass/baseQubit.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/python3
2
+ import math
3
+ class BaseQubit:
4
+ def __init__(self):
5
+ self.matrix = []
6
+ self.amplitude = []
7
+
8
+ def setAmp(self):
9
+ matrix = self.getMatrix()
10
+ self.amplitude = [0] * len(matrix)
11
+ for i in range(0,len(matrix)):
12
+ self.amplitude[i] = matrix[i][0]
13
+
14
+ #this function will be called when act a gate on the qubit
15
+ def setMatrix(self,newMatrix:list):
16
+ self.matrix = newMatrix
17
+ self.setAmp()
18
+
19
+ def getMatrix(self):
20
+ return self.matrix
21
+ def getAmp(self):
22
+ return self.amplitude
23
+
24
+ def normalize(self):
25
+ newMatrix = self.getMatrix()
26
+ sums = 0
27
+ for item in newMatrix:
28
+ sums += (item[0] * item[0].conjugate())
29
+ #the imag of the sums must be zero
30
+ denominator = math.sqrt(sums.real)
31
+ for i in range(0,len(newMatrix)):
32
+ newMatrix[i][0] = newMatrix[i][0] / denominator
33
+ #set the result to the amplitude and the matrix of the current instance
34
+ self.setMatrix(newMatrix)
35
+
36
+ #overwrite the multiply to express the tensor product
37
+ def __mul__(self,other):
38
+ newMatrix = []
39
+ selfMatrix = self.getMatrix()
40
+ otherMatrix = other.getMatrix()
41
+ for i in range(0,len(selfMatrix)):
42
+ for j in range(0,len(otherMatrix)):
43
+ item = []
44
+ item.append(selfMatrix[i][0] * otherMatrix[j][0])
45
+ newMatrix.append(item)
46
+ return newMatrix
47
+
48
+
49
+
-QuQ--master/doc/QSI-framework.png ADDED

Git LFS Details

  • SHA256: 5af2587c9815494b6c8c24bb6c895216b541d7d7dc5bbeaf088af2631414909f
  • Pointer size: 130 Bytes
  • Size of remote file: 65.5 kB
-QuQ--master/doc/QuanSim-FrameWork.png ADDED

Git LFS Details

  • SHA256: 89a7ef677eabf26dfe43ad35e2ea2b9581af47b47bcdf365b84f7347f4cddb2f
  • Pointer size: 130 Bytes
  • Size of remote file: 52.9 kB
-QuQ--master/doc/ibm-backend/ibmqx4-backend2017.10.25.png ADDED

Git LFS Details

  • SHA256: 63372eb6c9d08695b5692bfbcb4eee424a0c2ede7de7620740ce66ff9c6fd31a
  • Pointer size: 130 Bytes
  • Size of remote file: 55.6 kB
-QuQ--master/doc/ibm-backend/ibmqx5-backend2017.10.25-1.png ADDED

Git LFS Details

  • SHA256: 3c014139918f3a0ac70dad442a3771b70bd1ae6ba7118c8190487bf0ed9bd427
  • Pointer size: 130 Bytes
  • Size of remote file: 93.1 kB
-QuQ--master/pic/QuanSim-datatype.png ADDED

Git LFS Details

  • SHA256: 34a6c149c0687ab8c032b1daa3ddeea251bf65e2308a2ad4547de171095f96c5
  • Pointer size: 130 Bytes
  • Size of remote file: 18.7 kB
-QuQ--master/results/EXP2018-03-14-15.23.40/Logical-Level/circuit.jpg ADDED

Git LFS Details

  • SHA256: 11bc3db2198c20ee62a3c249d9b8dc6e7d472073b3ef0facdbcfa671091afd2f
  • Pointer size: 130 Bytes
  • Size of remote file: 28.9 kB
-QuQ--master/results/EXP2018-03-14-15.23.40/chart.jpg ADDED

Git LFS Details

  • SHA256: 3f12c43b18420ef103b807bee599ab4cce8c62bb4270d07fdb4dcda0db4e0c8d
  • Pointer size: 130 Bytes
  • Size of remote file: 62.1 kB
-QuQ--master/results/EXP2018-03-14-15.23.45/Logical-Level/circuit.jpg ADDED

Git LFS Details

  • SHA256: fc49ce81a1bb625fa11d3a9d31947fb431d36bb5c7ffd3b85a98055beef1ba60
  • Pointer size: 130 Bytes
  • Size of remote file: 40.2 kB
-QuQ--master/results/EXP2018-03-14-15.23.45/chart.jpg ADDED

Git LFS Details

  • SHA256: e56b25cc1a99f29941131971507a255e57e7b2a10e83c02d7006399b3067070f
  • Pointer size: 130 Bytes
  • Size of remote file: 62.8 kB
-QuQ--master/userCode/GroverN=8theory/circuit.jpg ADDED

Git LFS Details

  • SHA256: d86fdb55509c8156d3f6951474e2c3d6a8ce06b5f6859edc9ab74c182bd65af0
  • Pointer size: 130 Bytes
  • Size of remote file: 81.8 kB
-QuQ--master/userCode/ibmGroverN=8.tar ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4f9e1ab116c9883b20f9e9bd0ba98bf122db33ce64382ff4bc518fc8201b1cb3
3
+ size 737792
10-week-algorithm-excercise-master/Week_01/141/linked_list_cycle_test.go ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package main
2
+
3
+ import "testing"
4
+
5
+ func Test(t *testing.T) {
6
+ n1 := &ListNode{Val: 1}
7
+ n2 := &ListNode{Val: 2, Next: n1}
8
+ n3:= &ListNode{Val: 3, Next: n2}
9
+ n4 := &ListNode{Val: 4, Next: n3}
10
+
11
+ if hasCycle(n1) {
12
+ t.Fatalf("failed")
13
+ }
14
+ if hasCycle(n2) {
15
+ t.Fatalf("failed")
16
+ }
17
+ if hasCycle(n3) {
18
+ t.Fatalf("failed")
19
+ }
20
+ if hasCycle(n4) {
21
+ t.Fatalf("failed")
22
+ }
23
+
24
+ n1.Next = n2
25
+ if !hasCycle(n4) {
26
+ t.Fatalf("failed")
27
+ }
28
+ }
29
+
30
+ func Test2(t *testing.T) {
31
+ n1 := &ListNode{Val: 1}
32
+ n2 := &ListNode{Val: 2, Next: n1}
33
+ n3:= &ListNode{Val: 3, Next: n2}
34
+ n4 := &ListNode{Val: 4, Next: n3}
35
+ n1.Next = n3
36
+ if !hasCycle(n4) {
37
+ t.Fatalf("failed")
38
+ }
39
+ }
10-week-algorithm-excercise-master/Week_01/206/reverse_linked_list.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ class ListNode:
2
+ def __init__(self, x):
3
+ self.val = x
4
+ self.next = None
5
+
6
+
7
+ class Solution:
8
+ def reverseList(self, head: ListNode) -> ListNode:
9
+ if head is None:
10
+ return
11
+
12
+ head_new = head
13
+ while head.next is not None:
14
+ next_ = head.next
15
+ next_.next, head.next = head_new, next_.next
16
+ head_new = next_
17
+ return head_new
18
+
19
+ def test(self):
20
+ node1 = ListNode(1)
21
+ node2 = ListNode(2)
22
+ node3 = ListNode(3)
23
+ node4 = ListNode(4)
24
+
25
+ node2.next = node1
26
+ node3.next = node2
27
+ node4.next = node3
28
+
29
+ ans = self.reverseList(node1)
30
+ assert ans == node1
31
+
32
+ ans = self.reverseList(node2)
33
+ assert ans == node1
34
+
35
+ ans = self.reverseList(node1)
36
+ assert ans == node2
37
+
38
+ ans = self.reverseList(node4)
39
+ assert ans == node1
40
+
41
+ print("success")
42
+
43
+
44
+ if __name__ == "__main__":
45
+ Solution().test()
10-week-algorithm-excercise-master/Week_01/206/reverse_linked_list_test.go ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package main
2
+
3
+ import "testing"
4
+
5
+ func Test(t *testing.T) {
6
+ node1 := ListNode{Val: 1}
7
+ node2 := ListNode{Val: 2, Next: &node1}
8
+ node3 := ListNode{Val: 3, Next: &node2}
9
+ node4 := ListNode{Val: 4, Next: &node3}
10
+ node5 := ListNode{Val: 5, Next: &node4}
11
+ if ans := reverseList(&node1); ans != &node1 {
12
+ t.Fatalf("failed, got %v\n", (*ans).Val)
13
+ }
14
+
15
+ if ans := reverseList(&node2); ans != &node1 {
16
+ t.Fatalf("failed, got %v\n", (*ans).Val)
17
+ }
18
+
19
+ if ans := reverseList(&node1); ans != &node2 {
20
+ t.Fatalf("failed, got %v\n", (*ans).Val)
21
+ }
22
+
23
+ if ans := reverseList(&node5); ans != &node1 {
24
+ t.Fatalf("failed, got %v\n", (*ans).Val)
25
+ }
26
+ }
10-week-algorithm-excercise-master/Week_01/21/merge_two_sorted_lists.py ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ class ListNode:
2
+ def __init__(self, val=0, next=None):
3
+ self.val = val
4
+ self.next = next
5
+
6
+
7
+ class Solution:
8
+ def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
9
+ dummy = ListNode()
10
+ cur = dummy
11
+
12
+ while l1 is not None and l2 is not None:
13
+ if l1.val < l2.val:
14
+ cur.next = l1
15
+ l1 = l1.next
16
+ else:
17
+ cur.next = l2
18
+ l2 = l2.next
19
+ cur = cur.next
20
+ if l1 is not None:
21
+ cur.next = l1
22
+ else:
23
+ cur.next = l2
24
+ return dummy.next
10-week-algorithm-excercise-master/Week_01/24/swap_nodes_in_pairs.go ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package main
2
+
3
+ type ListNode struct {
4
+ Val int
5
+ Next *ListNode
6
+ }
7
+
8
+ func swapPairs0(head *ListNode) *ListNode {
9
+ if head == nil || head.Next == nil {
10
+ return head
11
+ }
12
+ next := head.Next
13
+ head.Next = swapPairs(next.Next)
14
+ next.Next = head
15
+ return next
16
+ }
10-week-algorithm-excercise-master/Week_01/641/design_circular_deque_test.go ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package main
2
+
3
+ import "testing"
4
+
5
+ func Test(t *testing.T) {
6
+ q := Constructor(3)
7
+ if !q.IsEmpty() {
8
+ t.Fatalf("failed")
9
+ }
10
+ if q.GetFront() != -1 {
11
+ t.Fatalf("failed")
12
+ }
13
+ q.InsertLast(3)
14
+ if ans := q.GetFront(); ans != 3 {
15
+ t.Fatalf("failed, ans: %d\n", ans)
16
+ }
17
+ if ans := q.GetRear(); ans != 3 {
18
+ t.Fatalf("failed, ans: %d\n", ans)
19
+ }
20
+ q.InsertLast(8)
21
+ if ans := q.GetFront(); ans != 3 {
22
+ t.Fatalf("failed, ans: %d\n", ans)
23
+ }
24
+ if ans := q.GetRear(); ans != 8 {
25
+ t.Fatalf("failed, ans: %d\n", ans)
26
+ }
27
+ q.InsertLast(20)
28
+ if !q.IsFull() {
29
+ t.Fatalf("failed")
30
+ }
31
+ if q.InsertLast(30) {
32
+ t.Fatalf("failed\n")
33
+ }
34
+ q.DeleteFront()
35
+ if ans := q.GetFront(); ans != 8 {
36
+ t.Fatalf("failed, ans: %d\n", ans)
37
+ }
38
+ if ans := q.GetRear(); ans != 20 {
39
+ t.Fatalf("failed, ans: %d\n", ans)
40
+ }
41
+ q.DeleteLast()
42
+ if ans := q.GetFront(); ans != 8 {
43
+ t.Fatalf("failed, ans: %d\n", ans)
44
+ }
45
+ if ans := q.GetRear(); ans != 8 {
46
+ t.Fatalf("failed, ans: %d\n", ans)
47
+ }
48
+ q.DeleteLast()
49
+ if ans := q.GetFront(); ans != -1 {
50
+ t.Fatalf("failed, ans: %d\n", ans)
51
+ }
52
+ if ans := q.GetRear(); ans != -1 {
53
+ t.Fatalf("failed, ans: %d\n", ans)
54
+ }
55
+ if !q.IsEmpty() {
56
+ t.Fatalf("failed")
57
+ }
58
+ }
10-week-algorithm-excercise-master/Week_01/70/climbing_stairs.go ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package main
2
+
3
+ func climbStairs(n int) int {
4
+ if n < 3 {
5
+ return n
6
+ }
7
+ f1, f2 := 1, 2
8
+ for i := 3; i <= n; i++ {
9
+ f2, f1 = f2 + f1, f2
10
+ }
11
+ return f2
12
+ }
13
+
14
+
10-week-algorithm-excercise-master/Week_01/84/largest_rectangle_in_histogram.go ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package main
2
+
3
+ func largestRectangleArea0(heights []int) int {
4
+ res := 0
5
+
6
+ for i := 0; i < len(heights); i++ {
7
+ l, r := i, i
8
+ for l > 0 && heights[l-1] >= heights[i] {
9
+ l--
10
+ }
11
+ for r < len(heights)-1 && heights[r+1] >= heights[i] {
12
+ r++
13
+ }
14
+ res = max(res, heights[i]*(r-l+1))
15
+ }
16
+ return res
17
+ }
18
+
19
+ func max(x, y int) int {
20
+ if x > y {
21
+ return x
22
+ }
23
+ return y
24
+ }
10-week-algorithm-excercise-master/Week_01/84/largest_rectangle_in_histogram2.go ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package main
2
+
3
+ func largestRectangleArea1(heights []int) int {
4
+ if len(heights) == 0 {
5
+ return 0
6
+ }
7
+ n := len(heights)
8
+ leftIdx := make([]int, n)
9
+ rightIdx := make([]int, n)
10
+ leftIdx[0] = -1
11
+ rightIdx[n-1] = n
12
+
13
+ for i := 1; i < n; i++ {
14
+ l := i - 1
15
+ for l >= 0 && heights[l] >= heights[i] {
16
+ l = leftIdx[l]
17
+ }
18
+ leftIdx[i] = l
19
+ }
20
+ for i := n - 2; i >= 0; i-- {
21
+ r := i + 1
22
+ for r < n && heights[r] >= heights[i] {
23
+ r = rightIdx[r]
24
+ }
25
+ rightIdx[i] = r
26
+ }
27
+ res := 0
28
+ for i := 0; i < n; i++ {
29
+ res = max(res, heights[i]*(rightIdx[i]-leftIdx[i]-1))
30
+ }
31
+ return res
32
+ }
10-week-algorithm-excercise-master/Week_01/88/merge_sorted_array2.go ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package main
2
+
3
+ func merge(nums1 []int, m int, nums2 []int, n int) {
4
+ l := m + n - 1
5
+ m--
6
+ n--
7
+ for m >= 0 && n >= 0 {
8
+ if nums1[m] > nums2[n] {
9
+ nums1[l] = nums1[m]
10
+ m--
11
+ } else {
12
+ nums1[l] = nums2[n]
13
+ n--
14
+ }
15
+ l--
16
+ }
17
+ if n >= 0 {
18
+ copy(nums1[:n+1], nums2[:n+1])
19
+ }
20
+ }
10-week-algorithm-excercise-master/Week_01/88/merge_sorted_array2.py ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import List
2
+
3
+
4
+ class Solution:
5
+ def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
6
+ """
7
+ Do not return anything, modify nums1 in-place instead.
8
+ """
9
+ l = m + n - 1
10
+ m -= 1
11
+ n -= 1
12
+
13
+ while m >= 0 and n >= 0:
14
+ if nums1[m] > nums2[n]:
15
+ nums1[l] = nums1[m]
16
+ m -= 1
17
+ else:
18
+ nums1[l] = nums2[n]
19
+ n -= 1
20
+ l -= 1
21
+ if n >= 0:
22
+ nums1[:n + 1] = nums2[:n + 1]
10-week-algorithm-excercise-master/Week_02/144/binary_tree_preorder_traversal.go ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package main
2
+
3
+ type TreeNode struct {
4
+ Val int
5
+ Left *TreeNode
6
+ Right *TreeNode
7
+ }
8
+
9
+ func preorderTraversal(root *TreeNode) []int {
10
+ res := make([]int, 0)
11
+
12
+ var preOrder func(node *TreeNode)
13
+ preOrder = func(node *TreeNode) {
14
+ if node != nil {
15
+ res = append(res, node.Val)
16
+ preOrder(node.Left)
17
+ preOrder(node.Right)
18
+ }
19
+ }
20
+ preOrder(root)
21
+ return res
22
+ }
10-week-algorithm-excercise-master/Week_02/144/binary_tree_preorder_traversal2.py ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import List
2
+
3
+
4
+ class TreeNode:
5
+ def __init__(self, x):
6
+ self.val = x
7
+ self.left = None
8
+ self.right = None
9
+
10
+
11
+ class Solution:
12
+ def preorderTraversal(self, root: TreeNode) -> List[int]:
13
+ res = []
14
+ stack = [root]
15
+
16
+ while len(stack) > 0:
17
+ node = stack.pop()
18
+ if node is not None:
19
+ res.append(node.val)
20
+ if node.right is not None:
21
+ stack.append(node.right)
22
+ if node.left is not None:
23
+ stack.append(node.left)
24
+ return res
25
+
26
+ def test(self):
27
+ n1 = TreeNode(1)
28
+ n2 = TreeNode(2)
29
+ n3 = TreeNode(3)
30
+
31
+ n1.right = n2
32
+ n2.left = n3
33
+
34
+ ans = self.preorderTraversal(n1)
35
+ assert ans == [1, 2, 3], f"ans: {ans}"
36
+ print("well done")
37
+
38
+
39
+ if __name__ == "__main__":
40
+ Solution().test()
10-week-algorithm-excercise-master/Week_02/144/binary_tree_preorder_traversal3.go ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package main
2
+
3
+ func preorderTraversal3(root *TreeNode) []int {
4
+ res := make([]int, 0)
5
+
6
+ for root != nil {
7
+ res = append(res, root.Val)
8
+ if root.Left == nil {
9
+ root = root.Right
10
+ } else {
11
+ pre := root.Left
12
+
13
+ for pre.Right != nil {
14
+ pre = pre.Right
15
+ }
16
+ pre.Right = root.Right
17
+ root = root.Left
18
+ }
19
+ }
20
+ return res
21
+ }
10-week-algorithm-excercise-master/Week_02/144/binary_tree_preorder_traversal3.py ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import List
2
+
3
+
4
+ class TreeNode:
5
+ def __init__(self, x):
6
+ self.val = x
7
+ self.left = None
8
+ self.right = None
9
+
10
+
11
+ class Solution:
12
+ def preorderTraversal(self, root: TreeNode) -> List[int]:
13
+ res = []
14
+
15
+ while root is not None:
16
+ res.append(root.val)
17
+ if root.left is None:
18
+ root = root.right
19
+ else:
20
+ pre = root.left
21
+ while pre.right is not None:
22
+ pre = pre.right
23
+ pre.right = root.right
24
+ root = root.left
25
+
26
+ return res
27
+
28
+ def test(self):
29
+ n1 = TreeNode(1)
30
+ n2 = TreeNode(2)
31
+ n3 = TreeNode(3)
32
+
33
+ n1.right = n2
34
+ n2.left = n3
35
+
36
+ ans = self.preorderTraversal(n1)
37
+ assert ans == [1, 2, 3], f"ans: {ans}"
38
+ print("well done")
39
+
40
+
41
+ if __name__ == "__main__":
42
+ Solution().test()
10-week-algorithm-excercise-master/Week_02/264/ugly_number_ii2.go ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package main
2
+
3
+ func nthUglyNumber2(n int) int {
4
+ dp := make([]int, n)
5
+ dp[0]=1
6
+ two := 0
7
+ three := 0
8
+ five := 0
9
+ for i := 1; i < n; i++ {
10
+ num := min(2*dp[two], 3*dp[three], 5*dp[five])
11
+ dp[i] = num
12
+ if 2*dp[two] == num {
13
+ two++
14
+ }
15
+ if 3*dp[three] == num {
16
+ three++
17
+ }
18
+ if 5*dp[five] == num {
19
+ five++
20
+ }
21
+ }
22
+ return dp[n-1]
23
+ }
24
+
25
+ func min(x, y, z int) int {
26
+ if x <= y && x <= z {
27
+ return x
28
+ }
29
+ if y <= x && y <= z {
30
+ return y
31
+ }
32
+ return z
33
+ }
10-week-algorithm-excercise-master/Week_02/264/ugly_number_ii2.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ class Solution:
2
+ def nthUglyNumber(self, n: int) -> int:
3
+ dp = [0] * n
4
+ dp[0] = 1
5
+
6
+ two = three = five = 0
7
+
8
+ for i in range(1, n):
9
+ num = min(2 * dp[two], 3 * dp[three], 5 * dp[five])
10
+ dp[i] = num
11
+ if 2 * dp[two] == num:
12
+ two += 1
13
+ if 3 * dp[three] == num:
14
+ three += 1
15
+ if 5 * dp[five] == num:
16
+ five += 1
17
+ return dp[-1]
18
+
19
+ def test(self):
20
+ for n, target in [
21
+ (1, 1),
22
+ (10, 12),
23
+ ]:
24
+ ans = self.nthUglyNumber(n)
25
+ assert ans == target, f"n: {n}, target: {target}"
26
+ print("well done")
27
+
28
+
29
+ if __name__ == "__main__":
30
+ Solution().test()
10-week-algorithm-excercise-master/Week_02/264/ugly_number_ii_test.go ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package main
2
+
3
+ import "testing"
4
+
5
+ func Test(t *testing.T) {
6
+ tests := []struct {
7
+ n int
8
+ target int
9
+ }{
10
+ {1, 1},
11
+ {10, 12},
12
+ }
13
+ for _, tt := range tests {
14
+ if ans := nthUglyNumber2(tt.n); ans != tt.target {
15
+ t.Fatalf("ans: %d, target: %d\n", ans, tt.target)
16
+ }
17
+ }
18
+ }
10-week-algorithm-excercise-master/Week_02/347/top_k_frequent_elements.go ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package main
2
+
3
+ func topKFrequent(nums []int, k int) []int {
4
+ counter := make(map[int]int, 0)
5
+ for _, n := range nums {
6
+ counter[n]++
7
+ }
8
+ data := make([][2]int, k)
9
+
10
+ i := 0
11
+ for key, v := range counter {
12
+ if i <= k-1 {
13
+ data[i] = [2]int{key, v}
14
+ if i == k-1 {
15
+ for j := k/2 - 1; j >= 0; j-- {
16
+ heaplify(data, j, k-1)
17
+ }
18
+ }
19
+ i++
20
+ } else if v > data[0][1] {
21
+ data[0][0] = key
22
+ data[0][1] = v
23
+ heaplify(data, 0, k-1)
24
+ }
25
+ }
26
+ res := make([]int, k)
27
+
28
+ for i := 0; i < k; i++ {
29
+ res[i] = data[i][0]
30
+ }
31
+ return res
32
+ }
33
+
34
+ func heaplify(arr [][2]int, root int, end int) {
35
+ for {
36
+ child := root*2 + 1
37
+ if child > end {
38
+ return
39
+ }
40
+ if child+1 <= end && arr[child][1] > arr[child+1][1] {
41
+ child++
42
+ }
43
+ if arr[root][1] < arr[child][1] {
44
+ return
45
+ }
46
+ arr[root], arr[child] = arr[child], arr[root]
47
+ root = child
48
+ }
49
+ }
10-week-algorithm-excercise-master/Week_02/347/top_k_frequent_elements2.go ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package main
2
+
3
+ func topKFrequent2(nums []int, k int) []int {
4
+ counter := make(map[int]int, 0)
5
+ for _, n := range nums {
6
+ counter[n]++
7
+ }
8
+ arr := make([][2]int, 0)
9
+ for key, v := range counter {
10
+ arr = append(arr, [2]int{key, v})
11
+ }
12
+ if len(arr) > k {
13
+ quickSearch(arr, 0, len(arr)-1, k)
14
+ }
15
+ res := make([]int, k)
16
+ for i := 0; i < k; i++ {
17
+ res[i] = arr[i][0]
18
+ }
19
+ return res
20
+ }
21
+
22
+ func quickSearch(arr [][2]int, left, right, k int) {
23
+ if n := partition(arr, left, right); n > k {
24
+ quickSearch(arr, left, n-1, k)
25
+ } else if n < k {
26
+ quickSearch(arr, n+1, right, k)
27
+ }
28
+ }
29
+
30
+ func partition(arr [][2]int, left, right int) int {
31
+ pivot := arr[right][1]
32
+ i := left - 1
33
+ for j := left; j < right; j++ {
34
+ if arr[j][1] >= pivot {
35
+ i++
36
+ arr[i], arr[j] = arr[j], arr[i]
37
+ }
38
+ }
39
+ i++
40
+ arr[i], arr[right] = arr[right], arr[i]
41
+ return i
42
+ }
10-week-algorithm-excercise-master/Week_02/347/top_k_frequent_elements_test.go ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package main
2
+
3
+ import (
4
+ "reflect"
5
+ "sort"
6
+ "testing"
7
+ )
8
+
9
+ func Test(t *testing.T) {
10
+ tests := []struct {
11
+ nums []int
12
+ k int
13
+ target []int
14
+ }{
15
+ {[]int{1}, 1, []int{1}},
16
+ {[]int{1, 1, 1, 2, 2, 3}, 2, []int{1, 2}},
17
+ }
18
+
19
+ for _, tt := range tests {
20
+ ans := topKFrequent2(tt.nums, tt.k)
21
+ sort.Ints(ans)
22
+ if !reflect.DeepEqual(ans, tt.target) {
23
+ t.Fatalf("target: %v, ans : %v\n", tt.target, ans)
24
+ }
25
+ }
26
+ }
10-week-algorithm-excercise-master/Week_02/429/n_ary_tree_level_order_traversal.go ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package main
2
+
3
+ type Node struct {
4
+ Val int
5
+ Children []*Node
6
+ }
7
+
8
+ func levelOrder(root *Node) [][]int {
9
+ res := make([][]int, 0)
10
+
11
+ var levelOrder func(node *Node, level int)
12
+ levelOrder = func(node *Node, level int) {
13
+ if node != nil {
14
+ if len(res) == level {
15
+ res = append(res, []int{node.Val})
16
+ } else {
17
+ res[level] = append(res[level], node.Val)
18
+ }
19
+ for i := 0; i < len(node.Children); i++ {
20
+ levelOrder(node.Children[i], level+1)
21
+ }
22
+ }
23
+ }
24
+ levelOrder(root, 0)
25
+ return res
26
+ }
10-week-algorithm-excercise-master/Week_02/429/n_ary_tree_level_order_traversal.py ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import List
2
+
3
+
4
+ class Node:
5
+ def __init__(self, val=None, children=None):
6
+ self.val = val
7
+ self.children = children
8
+
9
+
10
+ class Solution:
11
+ def levelOrder(self, root: 'Node') -> List[List[int]]:
12
+ res = []
13
+
14
+ def level_order(node: Node, level: int):
15
+ if node is not None:
16
+ if len(res) == level:
17
+ res.append([node.val])
18
+ else:
19
+ res[level].append(node.val)
20
+ for c in node.children:
21
+ level_order(c, level + 1)
22
+
23
+ level_order(root, 0)
24
+ return res
10-week-algorithm-excercise-master/Week_02/429/n_ary_tree_level_order_traversal2.go ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package main
2
+
3
+ func levelOrder2(root *Node) [][]int {
4
+ res := make([][]int, 0)
5
+ stack := []*Node{root}
6
+ level := 0
7
+ for len(stack) > 0 {
8
+ num := len(stack)
9
+ for i := 0; i < num; i++ {
10
+ if stack[i] != nil {
11
+ if len(res) == level {
12
+ res= append(res, []int{stack[i].Val})
13
+ } else {
14
+ res[level] = append(res[level], stack[i].Val)
15
+ }
16
+ for j := 0; j < len(stack[i].Children); j++ {
17
+ stack = append(stack, stack[i].Children[j])
18
+ }
19
+ }
20
+ }
21
+ stack = stack[num:]
22
+ level++
23
+ }
24
+ return res
25
+ }
10-week-algorithm-excercise-master/Week_02/49/group_anagrams.go ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package main
2
+
3
+ func groupAnagrams(strs []string) [][]string {
4
+ res := make([][]string, 0)
5
+ indexMap := make(map[string]int, 0)
6
+ for _, s := range strs {
7
+ ss := sortString(s)
8
+ if idx, ok := indexMap[ss]; !ok {
9
+ indexMap[ss] = len(indexMap)
10
+ res = append(res, []string{s})
11
+ } else {
12
+ res[idx] = append(res[idx], s)
13
+ }
14
+ }
15
+ return res
16
+ }
17
+
18
+ func sortString(str string) string {
19
+ sl := make([]rune, 26)
20
+
21
+ for _, c := range str {
22
+ sl[c-'a']++
23
+ }
24
+ return string(sl)
25
+ }
10-week-algorithm-excercise-master/Week_02/49/group_anagrams.py ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import List, Dict
2
+
3
+
4
+ class Solution:
5
+ def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
6
+ counter: Dict[tuple, List[str]] = {}
7
+
8
+ def count_char(s: str) -> tuple:
9
+ base = [0] * 26
10
+ for c in s:
11
+ base[ord(c) - ord('a')] += 1
12
+ return tuple(base)
13
+
14
+ for s in strs:
15
+ cc = count_char(s)
16
+ if cc in counter:
17
+ counter[cc].append(s)
18
+ else:
19
+ counter[cc] = [s]
20
+ return list(counter.values())
21
+
22
+ def test(self):
23
+ for strs, target in [
24
+ ([""], [[""]]),
25
+ (["a", "b"], [["a"], ["b"]]),
26
+ (["ab", "ba", "bb"], [["ab", "ba"], ["bb"]]),
27
+ ]:
28
+ ans = self.groupAnagrams(strs)
29
+ assert sorted(ans) == sorted(target)
30
+
31
+ print("all done")
32
+
33
+
34
+ if __name__ == "__main__":
35
+ Solution().test()
10-week-algorithm-excercise-master/Week_02/49/group_anagrams_test.go ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package main
2
+
3
+ import (
4
+ "reflect"
5
+ "testing"
6
+ )
7
+
8
+ func Test(t *testing.T) {
9
+ tests := []struct {
10
+ strs []string
11
+ target [][]string
12
+ }{
13
+ {[]string{""}, [][]string{{""}}},
14
+ {[]string{"a", "ab", "ba"}, [][]string{{"a"}, {"ab", "ba"}}},
15
+ {[]string{"eat", "tea", "tan", "ate", "nat", "bat"}, [][]string{{"eat", "tea", "ate"}, {"tan", "nat"}, {"bat"}},
16
+ }}
17
+
18
+ for _, tt := range tests {
19
+ if ans := groupAnagrams(tt.strs); !reflect.DeepEqual(ans, tt.target) {
20
+ t.Fatalf("target: %v, ans: %v\n", tt.target, ans)
21
+ }
22
+ }
23
+ }
10-week-algorithm-excercise-master/Week_02/589/n_ary_tree_preorder_traversal.go ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package main
2
+
3
+ type Node struct {
4
+ Val int
5
+ Children []*Node
6
+ }
7
+
8
+ func preorder(root *Node) []int {
9
+ res := make([]int, 0)
10
+ var preOrder func(node *Node)
11
+ preOrder = func(node *Node) {
12
+ if node != nil {
13
+ res = append(res, node.Val)
14
+ for i := 0; i < len(node.Children); i++ {
15
+ preOrder(node.Children[i])
16
+ }
17
+ }
18
+ }
19
+ preOrder(root)
20
+ return res
21
+ }
10-week-algorithm-excercise-master/Week_02/589/n_ary_tree_preorder_traversal.py ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import List
2
+
3
+
4
+ class Node:
5
+ def __init__(self, val=None, children=None):
6
+ self.val = val
7
+ self.children = children
8
+
9
+
10
+ class Solution:
11
+ def preorder(self, root: 'Node') -> List[int]:
12
+ res = []
13
+
14
+ def pre_order(node: Node):
15
+ if node is not None:
16
+ res.append(node.val)
17
+ for c in node.children:
18
+ pre_order(c)
19
+
20
+ pre_order(root)
21
+ return res
10-week-algorithm-excercise-master/Week_02/589/n_ary_tree_preorder_traversal2.go ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package main
2
+
3
+ func preorder2(root *Node) []int {
4
+ res := make([]int, 0)
5
+ stack := []*Node{root}
6
+
7
+ for len(stack) > 0 {
8
+ node := stack[len(stack)-1]
9
+ stack = stack[:len(stack)-1]
10
+ if node != nil {
11
+ res = append(res, node.Val)
12
+ for i := len(node.Children) - 1; i >= 0; i-- {
13
+ stack = append(stack, node.Children[i])
14
+ }
15
+ }
16
+ }
17
+ return res
18
+ }
10-week-algorithm-excercise-master/Week_02/589/n_ary_tree_preorder_traversal2.py ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import List
2
+
3
+
4
+ class Node:
5
+ def __init__(self, val=None, children=None):
6
+ self.val = val
7
+ self.children = children
8
+
9
+
10
+ class Solution:
11
+ def preorder(self, root: 'Node') -> List[int]:
12
+ res = []
13
+
14
+ stack = [root]
15
+ while stack:
16
+ node = stack.pop()
17
+ if node is not None:
18
+ res.append(node.val)
19
+ for i in range(len(node.children) - 1, -1, -1):
20
+ stack.append(node.children[i])
21
+ return res
10-week-algorithm-excercise-master/Week_02/590/n_ary_tree_postorder_traversal.go ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package main
2
+
3
+ type Node struct {
4
+ Val int
5
+ Children []*Node
6
+ }
7
+
8
+ func postorder(root *Node) []int {
9
+ res := make([]int, 0)
10
+ var postOrder func(node *Node)
11
+ postOrder = func(node *Node) {
12
+ if node != nil {
13
+ for i := 0; i < len(node.Children); i++ {
14
+ postOrder(node.Children[i])
15
+ }
16
+ res = append(res, node.Val)
17
+ }
18
+ }
19
+ postOrder(root)
20
+ return res
21
+ }
10-week-algorithm-excercise-master/Week_02/590/n_ary_tree_postorder_traversal2.go ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package main
2
+
3
+ func postorder2(root *Node) []int {
4
+ res := make([]int, 0)
5
+ stack := []*Node{root}
6
+
7
+ for len(stack) > 0 {
8
+ node := stack[len(stack)-1]
9
+ stack = stack[:len(stack)-1]
10
+ if node != nil {
11
+ res = append(res, node.Val)
12
+ for i := 0; i < len(node.Children); i++ {
13
+ stack = append(stack, node.Children[i])
14
+ }
15
+ }
16
+ }
17
+
18
+ for i, j := 0, len(res)-1; i < j; i, j = i+1, j-1 {
19
+ res[i], res[j] = res[j], res[i]
20
+ }
21
+ return res
22
+ }
10-week-algorithm-excercise-master/Week_02/590/n_ary_tree_postorder_traversal2.py ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import List
2
+
3
+
4
+ class Node:
5
+ def __init__(self, val=None, children=None):
6
+ self.val = val
7
+ self.children = children
8
+
9
+
10
+ class Solution:
11
+ def postorder(self, root: 'Node') -> List[int]:
12
+ res = []
13
+
14
+ stack = [root]
15
+ while len(stack) > 0:
16
+ node = stack.pop()
17
+ if node is not None:
18
+ res.append(node.val)
19
+ for c in node.children:
20
+ stack.append(c)
21
+ return res[::-1]
10-week-algorithm-excercise-master/Week_02/590/n_ary_tree_postorder_traversal_test.go ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package main
2
+
3
+ import (
4
+ "reflect"
5
+ "testing"
6
+ )
7
+
8
+ func Test(t *testing.T) {
9
+ n1 := &Node{Val: 1}
10
+ n2 := &Node{Val: 2}
11
+ n3 := &Node{Val: 3}
12
+ n4 := &Node{Val: 4}
13
+ n5 := &Node{Val: 5}
14
+ n1.Children = []*Node{n2, n3, n4}
15
+ n3.Children = []*Node{n5}
16
+
17
+ if ans := postorder2(n1); !reflect.DeepEqual(ans, []int{2, 5, 3, 4, 1}) {
18
+ t.Fatalf("ans: %v\n", ans)
19
+ }
20
+ }