diff --git a/-Api_avec_python-master/Api1.py b/-Api_avec_python-master/Api1.py new file mode 100644 index 0000000000000000000000000000000000000000..e214bf528ec4bfa37c1f9e0a928d7ea383de89ba --- /dev/null +++ b/-Api_avec_python-master/Api1.py @@ -0,0 +1,29 @@ +import requests + + +url = "htpps://swap.co/api/people/" + +print("bienvenue dans notre exemple") + + +while url is not None: + + print("") + + r = requests.get(url) + + data = r.json() + + url = data["next"] + + persosTab = data["results"] + + for perso in persosTab: + + homeworld = requests.get(perso["homeworld"]) + homeworldName = homeworld.json()["name"] + + + print(perso["name"] + "is a " + perso["la_couleur_des_yeux"] + "les_yeux" + perso["genre"] + + ", ils sont " + perso["la_couleur_des_cheveux "] + "cheveux_et_poids" + perso["mass"] + + ", il_vient_de_la_planete" + homeworldName + " ! 馃槝\n") \ No newline at end of file diff --git a/-Api_avec_python-master/ex.py b/-Api_avec_python-master/ex.py new file mode 100644 index 0000000000000000000000000000000000000000..98fafcccc918bc01dd7b5a8c182aa9e361bd6cd0 --- /dev/null +++ b/-Api_avec_python-master/ex.py @@ -0,0 +1,45 @@ +########### +# IMPORTS # +########### + +import requests + +# url va me servir 脿 changer de page dans la boucle while +url = "https://swapi.co/api/people/" + +print("Welcome to the Useless Star Wars Facts !") + +# Quand il n'y a plus de "page suivante", la page "next" sera 茅gale 脿 None +# Donc, je boucle sur url tant qu'elle n'est pas 茅gale 脿 None :) +while url is not None: + + ############################ + # R脡CUP脡RATION DES DONN脡ES # + ############################ + + print("") + # Je fais la requ锚te sur la page en cours, et je r茅cup猫re la data + r = requests.get(url) + data = r.json() + + # C'est ici que je change l'url pour avoir la page d'apr猫s :) + url = data["next"] + # Ce tableau est la liste de tous les personnages + persosTab = data["results"] + + ########################### + # UTILISATION DES DONN脡ES # + ########################### + + # Je fais ensuite une boucle qui parcourt tous les personnages + # et qui affiche plein d'infos sur eux :) + for perso in persosTab: + # Pour la plan猫te natale, je r茅cup猫re le lien fourni par l'API + # et je fais une requ锚te dessus pour r茅cup茅rer son nom ;) + homeworld = requests.get(perso["homeworld"]) + homeworldName = homeworld.json()["name"] + + # Et ici je fais un m茅ga print qui affiche tout ! + print(perso["name"] + " is a " + perso["eye_color"] + " eyed " + perso["gender"] + + ", he has " + perso["hair_color"] + " hair and weighs " + perso["mass"] + + ". He is from planet " + homeworldName + " ! 馃槝\n") \ No newline at end of file diff --git a/-QuQ--master/LICENSE b/-QuQ--master/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..8dada3edaf50dbc082c9a125058f25def75e625a --- /dev/null +++ b/-QuQ--master/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/-QuQ--master/baseClass/Bit.py b/-QuQ--master/baseClass/Bit.py new file mode 100644 index 0000000000000000000000000000000000000000..0609306fab337c344b7d9dc24e05dca584ebbefa --- /dev/null +++ b/-QuQ--master/baseClass/Bit.py @@ -0,0 +1,47 @@ +#!/usr/bin/python3 +#the Bit class represent the standard classical bit +#get the info about the function name and the line number +import sys + +class Bit: + idList = [] + def __init__(self,value = None,ids = None): + if value == None: + value = 0 + self.value = value + if ids == None: + if len(Bit.idList) == 0: + ids = 0 + else: + ids = max(Bit.idList) + 1 + self.ids = 'c' + str(ids) + else: + #the bit is generated by the measurement of Qubit + self.ids = 'q' + str(ids) + #the index of the current bit, the range is from 0 to n + if self.ids in Bit.idList: + from Error import IDRepeatError + sys.path.append('../tools/') + from interactCfg import writeErrorMsg + try: + raise IDRepeatError("The id of this bit has been used, please choose another id!") + except IDRepeatError as ir: + info = self.get_curl_info() + funName = info[0] + line = info[1] + writeErrorMsg(ir,funName,line) + Bit.idList.append(self.ids) + + #overwrite the add operator of bits + def __add__(self,other): + return (str(self.value) + str(other.value)) + #please note that the first argument must Bit and the second argument must be str + def __add__(self,other:str): + return (str(self.value) + other) + + def get_curl_info(self): + try: + raise Exception + except: + f = sys.exc_info()[2].tb_frame.f_back + return [f.f_code.co_name, f.f_lineno] diff --git a/-QuQ--master/baseClass/Gate.py b/-QuQ--master/baseClass/Gate.py new file mode 100644 index 0000000000000000000000000000000000000000..257e92da44e99ac903f4cf4d77ee7f5d7e5afd03 --- /dev/null +++ b/-QuQ--master/baseClass/Gate.py @@ -0,0 +1,368 @@ +#!/usr/bin/python3 +from baseGate import * + +#the dict will be used in SplitGate of Gate.py +elementGate = { + "X":"CNOT cq-0,tq-0;", + "Y":"Sd tq-0;CNOT cq-0,tq-0;S tq-0;", + "Z":"H tq-0;CNOT cq-0,tq-0;H tq-0;", + "H":"H tq-0;Sd tq-0;CNOT cq-0,tq-0;H tq-0;T tq-0;CNOT cq-0,tq-0;T tq-0;H tq-0;S tq-0;X tq-0;S cq-0;", + "S":"T tq-0;CNOT cq-0,tq-0;Td tq-0;CNOT cq-0,tq-0;", + "Sd":"Td tq-0;CNOT cq-0,tq-0;T tq-0;CNOT cq-0,tq-0;", + "T":"Rz(math.pi/8) tq-0;CNOT cq-0,tq-0;Rz(-math.pi/8) tq-0;CNOT cq-0,tq-0;", + "Td":"Rz(-math.pi/8) tq-0;CNOT cq-0,tq-0;Rz(math.pi/8) tq-0;CNOT cq-0,tq-0;", + "Rz":"Rz(alpha) tq-0;CNOT cq-0,tq-0;Rz(beta) tq-0;CNOT cq-0,tq-0;", + "Ry":"Ry(alpha) tq-0;CNOT cq-0,tq-0;Ry(beta) tq-0;CNOT cq-0,tq-0;", + #the alpha and beta is a angle, and will be replaced by parameter of CU and MCU + #alpha = -beta +} + +#split a gate to the elements in the Dic "allowGate" +class SplitGate: + def __init__(self): + self.allowSet = [] + for key in allowGate: + if key == 'M': + continue + self.allowSet.append(key) + + #get the info about the function name and the line number + def get_curl_info(self): + try: + raise Exception + except: + f = sys.exc_info()[2].tb_frame.f_back + return [f.f_code.co_name, f.f_lineno] + + #convert the c0 to c1 by addind a X gate on the control-qubit + #or restore the state of the control-qubit + def __convert0to1(self,cql:list,vl:list): + QASM = "" + for i in range(0,len(cql)): + if len(vl) == 1: + j = 0 + else: + j = i + if vl[j] == 0: + QASM += "X cq-" + str(i) + ";" + #then the circuit is equal to c1-c1-c1-c1...-U + return QASM + + #C-U means that this is a controlled-gate with only one control qubit + #return value is the QASM code + def CU(self,gateName:str,cq:Qubit,tq:Qubit,vl:list,angle = None,executeStatus = False): + QASM = "" + QASM += self.__convert0to1([cq],vl) + #all the control-gate can be split into CNOT and single-gate + singleGate = gateName.split("-")[1] + #the singleGate can only be an element of the set "Y,Z,H,S,Sd,T,Td,Rz,Ry" + tmpQASM = "" + #ignore the global phase + try: + tmpQASM = elementGate[singleGate] + if angle != None: + #the U is Ry or Rz + angleN = angle/2 + tmpQASM = tmpQASM.replace("alpha",str(angleN),1) + tmpQASM = tmpQASM.replace("beta",str(-angleN),1) + except KeyError: + info = get_curl_info() + writeErrorMsg("Gate: "+ singleGate + " hasn't been definded in Dict:elementGate in defines.py!",info[0],info[1]) + QASM += tmpQASM + QASM += self.__convert0to1([cq],vl) + if executeStatus: + return self.execute(QASM,[cq],[tq],gateName,angle) + return QASM + + #MC-U means that this is a controlled-gate with more than one control qubit + #MCU will be split to Toffoli and CCU + #return value is the QASM code of this MCU + def MCU(self,gateName:str,cql:list,tq:Qubit,vl:list,angle = None,executeStatus = False): + if gateName == "c1-c1-X" or gateName == "Toffoli": + QASM = self.__Toffoli(["cq-0","cq-1"],"tq-0") + else: + #the multi-controlled qubit gate "c1-c1-c1-c1...-X" can be split to a series of Toffoli gates + #then c1-c1-c1-c1...-U is same with this case + N = len(cql) + 1 + actualN = 2 * N -3 + for i in range(0,actualN-1): + if i % 2 == 0 and i > 0: + #insert an auxiliary qubit + cql.insert(i,Qubit(True)) + #the auxiliary qubit need NOT to use X gate to fix the state + vl.insert(i,1) + QASM = "" + QASM += self.__convert0to1(cql,vl) + for j in range(2,actualN-1,2): + QASM += self.__Toffoli(["cq-"+str(j-2),"cq-"+str(j-1)],"cq-"+str(j)) + #the rest of the circuit is CCU + #the CCU is Toffoli + singleG = gateName.split("-")[-1] + if singleG == "X": + QASM += self.__Toffoli(["cq-"+str(actualN-3),"cq-"+str(actualN-2)],"tq-0") + else: + #the general case: CCU + try: + if angle != None: + #the U is Rz or Ry + angleN = angle/2 + if singleG == "Rz": + QASM += "Rz("+ str(angleN) +") tq-0;" + QASM += self.__Toffoli(["cq-"+str(actualN-3),"cq-"+str(actualN-2)],"tq-0") + QASM += "Rz("+ str(-angleN) +") tq-0;" + QASM += self.__Toffoli(["cq-"+str(actualN-3),"cq-"+str(actualN-2)],"tq-0") + elif singleG == "Ry": + QASM += "Ry("+ str(angleN) +") tq-0;" + QASM += self.__Toffoli(["cq-"+str(actualN-3),"cq-"+str(actualN-2)],"tq-0") + QASM += "Ry("+ str(-angleN) +") tq-0;" + QASM += self.__Toffoli(["cq-"+str(actualN-3),"cq-"+str(actualN-2)],"tq-0") + else: + raise GateNameError(singleGate) + else: + if singleG == "Y": + QASM += "Sd tq-0;" + QASM += self.__Toffoli(["cq-"+str(actualN-3),"cq-"+str(actualN-2)],"tq-0") + QASM += "S tq-0;" + elif singleG == "Z": + QASM += "H tq-0;" + QASM += self.__Toffoli(["cq-"+str(actualN-3),"cq-"+str(actualN-2)],"tq-0") + QASM += "H tq-0;" + elif singleG == "H": + QASM += "H tq-0;Sd tq-0;" + QASM += self.__Toffoli(["cq-"+str(actualN-3),"cq-"+str(actualN-2)],"tq-0") + QASM += "H tq-0;T tq-0;" + QASM += self.__Toffoli(["cq-"+str(actualN-3),"cq-"+str(actualN-2)],"tq-0") + QASM += "T tq-0;H tq-0;S tq-0;X tq-0;" + QASM += "S cq-"+str(actualN-3)+";S cq-"+str(actualN-2)+";" + elif singleG == "S": + QASM += self.__Toffoli(["cq-"+str(actualN-3),"cq-"+str(actualN-2)],"tq-0") + QASM += "Td tq-0;" + QASM += self.__Toffoli(["cq-"+str(actualN-3),"cq-"+str(actualN-2)],"tq-0") + QASM += "T tq-0;T cq-"+str(actualN-3)+";T cq-"+str(actualN-2)+";" + elif singleG == "Sd": + QASM += self.__Toffoli(["cq-"+str(actualN-3),"cq-"+str(actualN-2)],"tq-0") + QASM += "T tq-0;" + QASM += self.__Toffoli(["cq-"+str(actualN-3),"cq-"+str(actualN-2)],"tq-0") + QASM += "Td tq-0;Td cq-"+str(actualN-3)+";Td cq-"+str(actualN-2)+";" + elif singleG == "T": + QASM += self.__Toffoli(["cq-"+str(actualN-3),"cq-"+str(actualN-2)],"tq-0") + QASM += "Rz(-math.pi/8) tq-0;" + QASM += self.__Toffoli(["cq-"+str(actualN-3),"cq-"+str(actualN-2)],"tq-0") + QASM += "Rz(math.pi/8) tq-0;Rz(math.pi/8) cq-"+str(actualN-3)+";Rz(math.pi/8) cq-"+str(actualN-2)+";" + elif singleG == "Td": + QASM += self.__Toffoli(["cq-"+str(actualN-3),"cq-"+str(actualN-2)],"tq-0") + QASM += "Rz(math.pi/8) tq-0;" + QASM += self.__Toffoli(["cq-"+str(actualN-3),"cq-"+str(actualN-2)],"tq-0") + QASM += "Rz(-math.pi/8) tq-0;Rz(-math.pi/8) cq-"+str(actualN-3)+";Rz(-math.pi/8) cq-"+str(actualN-2)+";" + else: + raise GateNameError(singleG) + except GateNameError as gne: + info = get_curl_info() + writeErrorMsg(gne,info[0],info[1]) + pass + QASM += self.__convert0to1(cql,vl) + #print(QASM) + + if executeStatus: + return self.execute(QASM,cql,[tq],gateName,angle) + return QASM + + #special-case, this is an important element in constructing MCU + #cqIndexL stands for the list of the index of the control-qubits in the cqL + #tqIndex stands for the index of the target qubit in the tqL + def __Toffoli(self,cqIndexL:list,id_tq:str): + id_cq0 = cqIndexL[0] + id_cq1 = cqIndexL[1] + QASM = "H "+id_tq+";CNOT "+id_cq1 + QASM += ","+id_tq+";Td "+id_tq+";CNOT "+id_cq0 + QASM += ","+id_tq+";T "+id_tq+";CNOT "+id_cq1 + QASM += ","+id_tq+";Td "+id_tq+";CNOT "+id_cq0 + QASM += ","+id_tq+";Td "+id_cq1+";T "+id_tq + QASM += ";CNOT "+id_cq0+","+id_cq1+";H "+id_tq + QASM += ";Td "+id_cq1+";CNOT "+id_cq0+","+id_cq1 + QASM += ";T "+id_cq0+";S "+id_cq1 +";" + #print(QASM) + return QASM + + #record the entire gate in circuit.qubitExecuteList + def __recordEG(self,gateName:str,cql:list,tql:list,angle = None): + resQL = cql.copy() + for tq in tql: + resQL.append(tq) + + #record the entire gate in circuit.qubitExecuteList + + i = 0 + while i < len(resQL): + if resQL[i].tag == "AX": + #the qubit is an auxiliary qubit + del resQL[i] + continue + i += 1 + + cG = [[0] * (2**len(resQL))] * (2**len(resQL)) + + #append the multi-controlled gate to Dict "allowGate", which is defined in baseGate.py + #allowGate[gateName] = len(resQL) + + #init the Gate instance + gate = Gate(resQL,cG,gateName) + if len(resQL) == 1: + c = gate.recordSingleExecution(True,angle) + #print(c.qubitExecuteList) + else: + c = gate.recordmultiExecution(True,angle) + #print(c.qubitExecuteList) + + #'er' is the QASM code generated by the other methods in this class + #note that all the Single-Gate and Double-Gate in this function shouldn't be stored in circuit.qubitExecuteList + def execute(self,er,cqL:list,tqL:list,gateName:str,angle = None): + self.__recordEG(gateName,cqL,tqL,angle) + #execute the component gate + erL = er.split(";") + for item in erL: + if item == "": + continue + tmpStr = item.split(" ") + gate = tmpStr[0] + import re + #if the gate has parameter + m = re.match("(.*)\((.*)\)(.*)", gate) + if m != None: + gate = m.group(1) + parameter = m.group(2) + exeStr = gate + "(" + parameter + "," + else: + exeStr = gate + "(" + q = tmpStr[1].split(",") + for i in range(0,len(q)): + qType = q[i].split("-")[0] + index = q[i].split("-")[1] + try: + if qType == "cq": + exeStr += "cqL[" + index + "]" + elif qType == "tq": + exeStr += "tqL[" + index + "]" + else: + raise ValueError + except ValueError: + info = self.get_curl_info() + writeErrorMsg("Qubit List: "+qtype+" isn't defined in Class SplitGate!",info[0],info[1]) + except IndexError: + info = self.get_curl_info() + writeErrorMsg("The index of the target element is our of range!",info[0],info[1]) + if i != len(q)-1: + exeStr += "," + exeStr += ",False)" + exec(exeStr) + + resQL = cqL.copy() + for tq in tqL: + resQL.append(tq) + return resQL + +#record stands for whether record the gate in qubitExecuteList +#the forceQuit stands for whether record the gate in qubitExecuteList and qubitExecuteListOD +def X(q:Qubit,record = True,forceQuit = False): + X = [[0,1],[1,0]] + gate = Gate([q],X,"X") + return gate.singleOperator(record,forceQuit = forceQuit) + +def Y(q:Qubit,record = True,forceQuit = False): + Y = [[0,-1j],[1j,0]] + gate = Gate([q],Y,"Y") + return gate.singleOperator(record,forceQuit = forceQuit) + +def Z(q:Qubit,record = True,forceQuit = False): + Z = [[1,0],[0,-1]] + gate = Gate([q],Z,"Z") + return gate.singleOperator(record,forceQuit = forceQuit) + +def I(q:Qubit,record = True,forceQuit = False): + I = [[1,0],[0,1]] + gate = Gate([q],I,"I") + return gate.singleOperator(record,forceQuit = forceQuit) + + +def H(q:Qubit,record = True,forceQuit = False): + H = [[1/math.sqrt(2),1/math.sqrt(2)],[1/math.sqrt(2),-1/math.sqrt(2)]] + gate = Gate([q],H,"H") + return gate.singleOperator(record,forceQuit = forceQuit) + +def S(q:Qubit,record = True,forceQuit = False): + S = [[1,0],[0,1j]] + gate = Gate([q],S,"S") + return gate.singleOperator(record,forceQuit = forceQuit) + +def Sd(q:Qubit,record = True,forceQuit = False): + Sd = [[1,0],[0,-1j]] + gate = Gate([q],Sd,"Sd") + return gate.singleOperator(record,forceQuit = forceQuit) + + +def T(q:Qubit,record = True,forceQuit = False): + T = [[1,0],[0,(1+1j)/math.sqrt(2)]] + gate = Gate([q],T,"T") + return gate.singleOperator(record,forceQuit = forceQuit) + +def Td(q:Qubit,record = True,forceQuit = False): + Td = [[1,0],[0,(1-1j)/math.sqrt(2)]] + gate = Gate([q],Td,"Td") + return gate.singleOperator(record,forceQuit = forceQuit) + +#all the single qubit gate can be constructed by the following two gate according to ZYZ decompose +#the argument "phi" is a rotation angle in radians +def Rz(phi,q:Qubit,record = True,forceQuit = False): + pows = 1j*phi / 2 + Rz = [[cmath.exp(-pows),0],[0,cmath.exp(pows)]] + gate = Gate([q],Rz,"Rz") + return gate.singleOperator(record,phi,forceQuit = forceQuit) + +def Ry(theta,q:Qubit,record = True,forceQuit = False): + Ry = [[math.cos(theta/2),-math.sin(theta/2)],[math.sin(theta/2),math.cos(theta/2)]] + gate = Gate([q],Ry,"Ry") + return gate.singleOperator(record,theta,forceQuit = forceQuit) + +#this gate is implemented by Rz and Ry +def Rx(phi,q:Qubit,record = True,forceQuit = False): + PI = math.pi + I = [[1,0],[0,1]] + q = Rz(PI/2,q,False) + q = Ry(-phi,q,False) + q = Rz(-PI/2,q,False) + gate = Gate([q],I,"Rx") + gate.recordSingleExecution(True,phi,forceQuit = forceQuit) + return q + + +#return a Qubits, which has two entanglement qubit +#the two qubit can be independent qubits, or one of them are a part of engtanlement +#the first qubit is the control-qubit, the second qubit is the target-qubit +def CNOT(q1:Qubit,q2:Qubit,record = True,forceQuit = False): + CNOT = [[1,0,0,0],[0,1,0,0],[0,0,0,1],[0,0,1,0]] + gate = Gate([q1,q2],CNOT,"CNOT") + return gate.CNOTOperator(record,forceQuit = forceQuit) + + +def ControlledZ(q1:Qubit,q2:Qubit,record = True,forceQuit = False): + H(q2,record,forceQuit) + CNOT(q1,q2,record,forceQuit) + H(q2,record,forceQuit) + return q1.entanglement + +#execute the measurement, the types of the first argument must be Qubit; the second argument is optional, +#if the parameter "result" is "False", then the result of the measurement won't be appeared in the end result +def M(q:Qubit,result = True): + I = [[1,0],[0,1]] + #print([q]) + gate = Gate([q],I,"M") + #the measurement will return a Bit type + #but the qubit "q" is still a Qubit and the status of it is |0> or |1> according to the value of the Bit + return gate.MOperator(result) + + +#Toffoli gate, three input and three output +def Toffoli(q1:Qubit,q2:Qubit,q3:Qubit): + sg = SplitGate() + qL = sg.MCU("Toffoli",[q1,q2],q3,[1,1],None,True) + return qL diff --git a/-QuQ--master/baseClass/IBMQX.py b/-QuQ--master/baseClass/IBMQX.py new file mode 100644 index 0000000000000000000000000000000000000000..eaf6591799bd4bd5f6cdac6f4b02e35f401e4203 --- /dev/null +++ b/-QuQ--master/baseClass/IBMQX.py @@ -0,0 +1,680 @@ +#!/usr/bin/python3 +#import the ibm code +from IBMQuantumExperience import * +from interactCfg import * +from helperFunction import * +from Error import * +import os +import sys +import re +from Gate import SplitGate +import time + +#get the info about the function name and the line number +def get_curl_info(): + try: + raise Exception + except: + f = sys.exc_info()[2].tb_frame.f_back + return [f.f_code.co_name, f.f_lineno] + +qasmDic = { + "I":"id", + "X":"x", + "Y":"y", + "Z":"z", + "H":"h", + "S":"s", + "T":"t", + "CNOT":"cx", + "Td":"tdg", + "Sd":"sdg", + "M":"measure", + "Rz":"u1", + "Ry":"u3" +} + +#the max execute times is made by IBM stuff +MAXTIMES = 8192 +#the min executive times is made by IBM stuff +MINTIMES = 1 + +class IBMQX: + def __init__(self): + print("Connecting to the Server...") + #change the config message in config/IBMToken.cfg + tokenDic = readCfgPM() + self.__config = { + "url": tokenDic['url'] + } + #init the api + self.api = IBMQuantumExperience(tokenDic['token'], self.__config) + print("Getting the available backend information...") + deviceList = self.__getAvailalbeBak() + self.device = tokenDic['device'] + self.shot = int(tokenDic['shot']) + if self.device not in deviceList: + try: + raise IBMError("The seleted device isn't available") + except IBMError as ie: + info = get_curl_info() + funName = info[0] + line = info[1] + writeErrorMsg(ie.value,funName,line) + if self.shot < MINTIMES or self.shot > MAXTIMES: + try: + raise IBMError("The execute times must be from " + str(MINTIMES) + " to " + str(MAXTIMES) + ", but the input is " + str(self.shot)) + except IBMError as ie: + info = get_curl_info() + funName = info[0] + line = info[1] + writeErrorMsg(ie.value,funName,line) + #get the connectivity map of the device according to the name of the device + try: + dic = tokenDic['connectivity'][self.device] + #change the key and item from str to int + self.connectivity = {} + for key in dic: + for item in dic[key]: + if int(key) in self.connectivity: + self.connectivity[int(key)].append(int(item)) + else: + self.connectivity[int(key)] = [int(item)] + except KeyError as ke: + info = get_curl_info() + funName = info[0] + line = info[1] + writeErrorMsg("the IBMToken.cfg doesn't have the connectivity of the current device: " + self.device,funName,line) + #create a new folder to save the data of IBMQX + circuit = checkEnvironment() + if os.path.exists(circuit.urls + "/IBMQX") == False: + try: + os.makedirs(circuit.urls + "/IBMQX") + except OSError: + info = get_curl_info() + funName = info[0] + line = info[1] + interactCfg.writeErrorMsg("Can't create the new folder 'IBMQX'!",funName,line) + + #get the availalbe backend, return the backend list + def __getAvailalbeBak(self): + result = [] + lists = self.api.available_backends() + for item in lists: + try: + backend = item['name'] + result.append(backend) + except KeyError: + info = get_curl_info() + funName = info[0] + line = info[1] + writeErrorMsg("Can't get the key:'name' in the backend information!".funName,line) + return result + + #translate the QASM to Open-QASM + #the parameter 'c' is the current Circuit instance + + #return True: translate successfully! + #return False: there is if statement in the QASM code + def __translateQASM(self,c): + global QASM + #the code has been store in circuit.url/QASM.txt + codeLocation = c.urls + "/Physical-Level/QASM.txt" + #this function must be called after circuit.execute() + if os.path.exists(codeLocation) == False: + info = get_curl_info() + funName = info[0] + line = info[1] + writeErrorMsg("The QASM code hasn't been generated, please check your code!",funName,line) + file = open(codeLocation) + codes = file.readlines() + file.close() + + for item in codes: + #whether the statement is "if" + if re.search(r'if(.+)',item) != None: + return False + tmpCode = "" + tmp = item.split(" ") + gate = tmp[0] + #if the gate is M: M q[0] -> c[0], we have to get the tmp[1:len] + qubitL = tmp[1:len(tmp)] + try: + para = None + if re.search(r'^R\w{1}\(.+\)$',gate) != None: + #the gate is Rn and has the parameter + para = gate.split("(")[1].split(")")[0] + gate = gate.split("(")[0] + + gate = qasmDic[gate] + if gate == "u1": + gate += "(" + para + ")" + if gate == "u3": + gate += "(" + para + ",0,0)" + #the gate with parameter + tmpCode += gate + " " + for q in qubitL: + tmpCode += q + except KeyError: + info = get_curl_info() + funName = info[0] + line = info[1] + #print(tmpCode) + QASM.append(tmpCode) + return True + + + #adjust the QASM code, which is producted by circuit.QASM(), so that the qubits can satisfy the constraint + #of the CNOT connectivity + def __canExecute(self): + circuit = checkEnvironment() + if circuit == None: + return None + global QASM,qubitList,CNOTList + QASM = [] + #record the reason for why can't execute the code + reasonList = [] + print("Translating the QASM to Open-QASM...") + if self.__translateQASM(circuit): + #translate successfully! + print("Optimizing the Open-QASM code, please wait for a while...") + + #record the ids of qubits in the current circuit + qubitList = [] + #record the cnot map in the current circuit + CNOTList = [] + + #find the num in the str + mode = re.compile(r'\d+') + #analyse the QASM code + for l in range(0,len(QASM)): + if l == 0: + continue + else: + qs = mode.findall(QASM[l]) + if "measure" in QASM[l]: + qs = [qs[0]] + for q in qs: + if int(q) in qubitList: + continue + else: + qubitList.append(int(q)) + if "cx" in QASM[l]: + #get the id of control-qubit and target-qubit + tQ = int(qs[1]) + cQ = int(qs[0]) + #the reverse cnot won't be appended to the list + if [cQ,tQ] in CNOTList or [tQ,cQ] in CNOTList: + continue + CNOTList.append([cQ,tQ]) + + totalConnectivity = self.__getTotalConnectivity() + + cnotBool = True + idBool = True + idBool = self.__determindID(totalConnectivity,reasonList) + if idBool: + cnotBool = self.__checkAllConstraint(CNOTList,totalConnectivity) + if cnotBool == False: + #when __adjustCNOT was called, the CNOTList doesn't satisfy the constraint of IBM directly + cnotBool = self.__adjustCNOT(totalConnectivity,reasonList) + + #the circuit can be executed + if idBool & cnotBool: + numQ = str(len(totalConnectivity)) + code = 'OPENQASM 2.0;include "qelib1.inc";qreg q[' + numQ + '];creg c[' + numQ + '];\n' + self.__reverseCNOT() + for line in QASM: + code += line + try: + file = open(circuit.urls + "/IBMQX/Open-QASM.txt","w") + file.write(code) + file.close() + except IOError: + info = get_curl_info() + funName = info[0] + line = info[1] + writeErrorMsg("Can't write QASM code to Open-QASM.txt!",funName,line) + return code + else: + #if statement + reasonList.append("The Mif and Qif aren't supported by IBMQX for now!") + + #if statement or there is something wrong with the number of qubits or connectivity of qubits + self.__writeErrorMsg(circuit.urls,reasonList) + + + #write the reason why the code can't be executed on IBMQX + def __writeErrorMsg(self,urls,reasonList:list): + #can't execute the circuit + file = open(urls + "/IBMQX/codeWarning.txt",'a') + file.write("WARNING:\n") + #write the reason in codeWarning.txt + for i in range(0,len(reasonList)): + strs = str(i+1) + "." + reasonList[i] + "\n" + file.write(strs) + return None + + #add self.connectivity and reverse self.connectivity, the type of the returned parameter is dict + def __getTotalConnectivity(self): + totalConnectivity = {} + for cQ in self.connectivity: + for tQ in self.connectivity[cQ]: + if cQ in totalConnectivity: + totalConnectivity[cQ].append(tQ) + else: + totalConnectivity[cQ] = [tQ] + if tQ in totalConnectivity: + totalConnectivity[tQ].append(cQ) + else: + totalConnectivity[tQ] = [cQ] + return totalConnectivity + + #determind whether the number of qubit in this circuit is more than the actual number + #if bigger, return False; else return True; + #if necessary, adjust the id of the qubit so that they are in line with the actual device + def __determindID(self,totalConnectivity,reasonList): + #we assume that there is no qubit isolated in ibm chip! + useQubit = len(qubitList) + actualQubit = len(totalConnectivity) + if useQubit > actualQubit: + reasonList.append("There are "+ str(useQubit) + " have been used! But the device you choose only have " + str(actualQubit) + " qubits!") + return False + if max(qubitList) < actualQubit: + return True + qubitList.sort() + availalbleQ = [i for i in range(0,actualQubit)] + qMap = {} + for q in qubitList: + qMap[q] = q + if q < actualQubit: + try: + availalbleQ.remove(q) + except ValueError: + info = get_curl_info() + funName = info[0] + line = info[1] + writeErrorMsg("Q "+ str(q) + " isn't available!",funName,line) + continue + #q >= actualQubit + #because actualQubit is more than useQubit, the actualQubit[0] is always existing + qMap[q] = availalbleQ[0] + availalbleQ.remove(availalbleQ[0]) + self.__changeQASMandCNOT(qMap) + return True + + #check the CNOT list whether satisfies the constraint of the connectivity + #if satisfies or we can adjust the cnot to satisfy the constraint, return True; + #else return False and store the 'bad' cnot in reasonList + def __adjustCNOT(self,totalConnectivity,reasonList): + cnotNum = len(CNOTList) + ibmNum = 0 + for k in self.connectivity: + ibmNum += len(self.connectivity[k]) + if cnotNum > ibmNum: + reason = "There are " + str(cnotNum) + " different connectivities in this circuit, but only " + str(ibmNum) + " are allowd in IBM chip!" + reasonList.append(reason) + return False + totalCNOT = {} + cnotQList = [] + for cnot in CNOTList: + if cnot[0] not in cnotQList: + cnotQList.append(cnot[0]) + if cnot[1] not in cnotQList: + cnotQList.append(cnot[1]) + if cnot[0] in totalCNOT: + totalCNOT[cnot[0]].append(cnot[1]) + else: + totalCNOT[cnot[0]] = [cnot[1]] + if cnot[1] in totalCNOT: + totalCNOT[cnot[1]].append(cnot[0]) + else: + totalCNOT[cnot[1]] = [cnot[0]] + choiceList = [] + for cq in totalCNOT: + tmp = [] + for tcq in totalConnectivity: + if len(totalConnectivity[tcq]) >= len(totalCNOT[cq]): + tmp.append(tcq) + choiceList.append(tmp) + #the solution space is choiceList[] + solution = [-1] * len(cnotQList) + newMaps = self.__backTrace(0,len(cnotQList),solution,totalConnectivity,choiceList,cnotQList) + if newMaps != None: + self.__changeQASMandCNOT(newMaps) + return True + else: + reason = "Can't adjust the connectivity in your circuit to satisfy the requirement of the IBM chip!" + reasonList.append(reason) + return False + def __backTrace(self,depth,N,solution,tc,choiceList,cnotQList): + if depth >= N: + dic = self.__getQubitMap(cnotQList,solution,tc) + if self.__checkMapConstraint(dic,tc): + return dic + else: + return None + else: + for i in range(0,len(choiceList[depth])): + if choiceList[depth][i] in solution[0:depth+1]: + continue + else: + solution[depth] = choiceList[depth][i] + res = self.__backTrace(depth+1,N,solution,tc,choiceList,cnotQList) + if res != None: + return res + + #use two list to construct a map: the key is from the first list and the value is from the second list + #note: the dimension of l1 and l2 must be same with each other + #and if there is qubits in qubitList but not in CNOTList, we should append the item in the dict + def __getQubitMap(self,l1,l2,tc): + if len(l1) != len(l2): + try: + raise IBMError("The dimension of the Qubit list should be same with the dimension of the solution!") + except IBMError as ie: + info = get_curl_info() + funName = info[0] + line = info[1] + writeErrorMsg(ie.value,funName,line) + dic = {} + availalbleQ = [i for i in range(0,len(tc))] + + for index in range(0,len(l1)): + dic[l1[index]] = l2[index] + availalbleQ.remove(l2[index]) + + for q in qubitList: + if q in dic: + continue + else: + dic[q] = availalbleQ[0] + del availalbleQ[0] + return dic + + #adjust the copy of CNOTList according to the map, and call the __checkAllConstraint + def __checkMapConstraint(self,maps,tc): + if len(maps) != len(qubitList): + return False + cCNOTList = CNOTList.copy() + for i in range(0,len(cCNOTList)): + cCNOTList[i] = [maps[cCNOTList[i][0]],maps[cCNOTList[i][1]]] + return self.__checkAllConstraint(cCNOTList,tc) + + #change the global parameter qubitList, QASM, CNOTList according to the qmap + def __changeQASMandCNOT(self,qMap): + global QASM + #change the id in CNOTList to satisfy the requirement + for i in range(0,len(CNOTList)): + for j in range(0,len(CNOTList[i])): + CNOTList[i][j] = qMap[CNOTList[i][j]] + + #change the QASM code + mode = re.compile(r'\d+') + for l in range(0,len(QASM)): + if l == 0: + continue + else: + qs = mode.findall(QASM[l]) + if len(qs) == 1: + #single-qubit gate + QASM[l] = QASM[l].replace("[" + str(qs[0]) + "]","[" + str(qMap[int(qs[0])]) + "]") + elif len(qs) == 2 and qs[0] == qs[1]: + #measurement + QASM[l] = QASM[l].replace("[" + str(qs[0]) + "]","[" + str(qMap[int(qs[0])]) + "]") + else: + #multi-qubits gate + newQASM = QASM[l].split(" ")[0] + " " + qubit = QASM[l].split(" ")[1].split(",") + for qi in range(0,len(qs)): + newQASM += qubit[qi].replace("[" + str(qs[qi]) + "]","[" + str(qMap[int(qs[qi])]) + "]") + if qi != len(qs)-1: + newQASM += "," + QASM[l] = newQASM + + #change the qubitList according to the qMap + for qi in range(0,len(qubitList)): + if qubitList[qi] in qMap: + qubitList[qi] = qMap[qubitList[qi]] + + #the the max neighbor in totalconnectivity + def __getMaxNeighbor(self,tc): + if type(tc) != dict: + try: + raise TypeError + except TypeError: + info = get_curl_info() + funName = info[0] + line = info[1] + writeErrorMsg("The type of the argument must be Dict!",funName,line) + maxs = 0 + for c in tc: + maxs = max(maxs,len(tc[c])) + return maxs + + #check cnot whether satisfies the constraint + #the format of cnot should be [1,3] + def __checkSingleConstraint(self,cnot:list,tc): + if len(cnot) != 2: + try: + raise ValueError + except ValueError: + info = get_curl_info() + funName = info[0] + line = info[1] + writeErrorMsg("The cnot should be two-dimension!",funName,line) + cQ = cnot[0] + tQ = cnot[1] + if cQ in tc and tQ in tc[cQ]: + #directly satisfy the constraint + return True + else: + return False + def __checkAllConstraint(self,cnotList,tc): + for c in cnotList: + if self.__checkSingleConstraint(c,tc): + continue + else: + return False + return True + + #get the legal cnot gate in current device + def __getLegalCNOT(self): + legalCList = [] + for cQ in self.connectivity: + for tQ in self.connectivity[cQ]: + if [cQ,tQ] not in legalCList: + legalCList.append([cQ,tQ]) + if [tQ,cQ] not in legalCList: + legalCList.append([tQ,cQ]) + return legalCList + + #modify the qasm code by adding H to reverse the current CNOT + def __reverseCNOT(self): + lineN = 0 + while lineN < len(QASM): + if 'cx' in QASM[lineN]: + q = QASM[lineN].split(" ")[1] + strs = q.split(',') + #get the id of control-qubit and target-qubit + tQ = int(strs[1][2]) + cQ = int(strs[0][2]) + if tQ in self.connectivity and cQ in self.connectivity[tQ]: + #add H gate to satisfy the constraint + hExternal = "h q[" + str(cQ) + "];\r\nh q[" + str(tQ) + "];\r\n" + gateStr = "cx q[" + str(cQ) + "],q[" + str(tQ) + "];" + if gateStr in QASM[lineN]: + QASM.insert(lineN,hExternal) + QASM[lineN+1] = "cx q[" + str(tQ) + "],q[" + str(cQ) + "];\r\n" + QASM.insert(lineN+2,hExternal) + lineN += 1 + + #execute the code + def executeQASM(self,experimentName = None): + code = self.__canExecute() + circuit = checkEnvironment() + if code == None: + info = get_curl_info() + funName = info[0] + line = info[1] + writeErrorMsg("The QASM code generated by QuanSim doesn't satisfy the requirement of IBMQX!",funName,line) + return False + try: + data = self.api.run_experiment(code,self.device,self.shot,experimentName,timeout = 300) + except ConnectionError as ce: + info = get_curl_info() + funName = info[0] + line = info[1] + writeErrorMsg("Can't connect to the server, Please try again later!",funName,line) + res = self.__analyseData(data) + + #get the result analysed + if res['status'] == 0: + #waiting + blank = {} + resOfExe = self.__query(res['msg']) + if resOfExe == blank: + print("The experiment is still waiting in the executive queue, We'll query every 5 seconds! You can also find the result on the Web of IBM Quantum Experience!") + while resOfExe == blank: + #still no result + print("Waiting in the queue...") + #sleep for 5 seconds + time.sleep(5) + resOfExe = self.__query(res['msg']) + #get the result + self.__writeRaWData(resOFExe) + measure = resOFExe['measure'] + qubits = measure['qubits'] + labels = measure['labels'] + values = measure['values'] + rList = [] + for i in range(0,len(labels)): + states = "" + for q in qubits: + state = labels[i][len(labels[i])-q-1] + states += state + rList.append([states,values[i]]) + dataMsg = "-" * 30 + dataMsg += " the data of IBMQX " + dataMsg += "-" * 31 + dataMsg += "\r\n" + dataMsg += "Result:\r\n" + for r in rList: + prob = float(r[1]) * 100 + dataMsg += " "*8+"|" + r[0] + ">----%.2f%%"%(prob) + dataMsg += "\r\n" + dataMsg += "-" * 80 + print(dataMsg) + self.__writeAnalyData(dataMsg) + + elif res['status'] == 2: + #wrong + self.__writeRaWData(data) + else: + #successful + self.__writeRaWData(data) + self.__writeAnalyData(res['msg']) + + + + #analyse the date + ############################################## + #the return value is a Dict{'status':0,"msg":None} + #if successful, then status is 1 and msg is the data analysed + #if waiting, then status is 0 and msg is the id of the experiment + #if error, then status is 2 and msg is None + ############################################### + def __analyseData(self,data): + res = {'status':0,"msg":None} + try: + #judge the status of the experiment + status = data['status'] + if status == "WORKING_IN_PROGRESS": + #still in queue + #then get the id of the experiment + ids = data['idExecution'] + res['status'] = 0 + res['msg'] = ids + return res + + elif status == "": + #successful + status = data['status'] + result = data['result'] + measure = result['measure'] + qubits = measure['qubits'] + labels = measure['labels'] + values = measure['values'] + rList = [] + for i in range(0,len(labels)): + states = "" + for q in qubits: + state = labels[i][len(labels[i])-q-1] + states += state + rList.append([states,values[i]]) + dataMsg = "-" * 30 + dataMsg += " the data of IBMQX " + dataMsg += "-" * 31 + dataMsg += "\r\n" + dataMsg += "Result:\r\n" + for r in rList: + prob = float(r[1]) * 100 + dataMsg += " "*8+"|" + r[0] + ">----%.2f%%"%(prob) + dataMsg += "\r\n" + dataMsg += "-" * 80 + print(dataMsg) + res['status'] = 1 + res['msg'] = dataMsg + return res + + else: + #there is something wrong + res['status'] = 2 + res['msg'] = None + return 1 + + except KeyError: + info = get_curl_info() + funName = info[0] + line = info[1] + writeErrorMsg("There are some keys aren't in the result returned by IBMQX!",funName,line) + + #write the raw data of IBMQX to file + def __writeRaWData(self,rawData): + if rawData == "": + return False + #write the date to file + try: + rawDataFile = open(circuit.urls + "/IBMQX/rawData_IBMQX.txt","w",encoding='utf-8') + rawDataFile.write(rawData) + rawDataFile.close() + except IOError: + info = get_curl_info() + funName = info[0] + line = info[1] + writeErrorMsg("Can't write the raw data of IBMQX to rawData_IBMQX.txt!",funName,line) + + #write the data analysed of IBMQX to file + def __writeAnalyData(self,data): + if data == "": + return False + #write the data to Data_IBMQX.txt + try: + dataFile = open(circuit.urls + "/IBMQX/Data_IBMQX.txt","w",encoding='utf-8') + dataFile.write(Data) + dataFile.close() + except IOError: + info = get_curl_info() + funName = info[0] + line = info[1] + writeErrorMsg("Can't write the data of IBMQX to Data_IBMQX.txt!",funName,line) + + #get information (including the Code information) about a specific Execution of a Code, + #the parameter "id_execution" is the id of the experiment + def __query(self,id_execution): + res = self.api.get_result_from_execution(id_execution) + # print(res) + return res + + def test(self): + res = self.api.get_result_from_execution("ff5b9f00a8333ee1f5586699c45a5bc8") + print(res) diff --git a/-QuQ--master/baseClass/baseCF.py b/-QuQ--master/baseClass/baseCF.py new file mode 100644 index 0000000000000000000000000000000000000000..0248c63bd110a721c3f12db69143ce15d9383889 --- /dev/null +++ b/-QuQ--master/baseClass/baseCF.py @@ -0,0 +1,46 @@ +from Qubit import * +sys.path.append('../tools/') +from interactCfg import writeErrorMsg +from helperFunction import get_curl_info + +class ControlFlow: + def __init__(self,q,v): + self.ql = [] + self.vl = [] + typeQ = type(q) + typeV = type(v) + if typeQ == Qubit and typeV == int: + self.ql.append(q) + self.vl.append(v) + elif typeQ == list and typeV == list: + if len(q) != len(v): + try: + raise ValueError() + except ValueError as t: + info = get_curl_info() + funName = info[0] + line = info[1] + writeErrorMsg("The length of the qubit list should be same with the length of the value list!",funName,line) + if repeatElement(q): + info = get_curl_info() + writeErrorMsg("There are repeating elements in the control-qubits list!",info[0],info[1]) + self.ql = q + self.vl = v + elif typeQ == list and typeV == int: + self.ql = q + self.vl.append(v) + else: + try: + raise TypeError() + except TypeError as t: + info = get_curl_info() + funName = info[0] + line = info[1] + writeErrorMsg("The types of the two arguments aren't allowed,\ + they should be (Qubit,int),(list,list) or (list,int)!",funName,line) + + def __enter__(self): + return True + def __exit__(self,a,b,c): + pass + diff --git a/-QuQ--master/config/IBMToken.cfg b/-QuQ--master/config/IBMToken.cfg new file mode 100644 index 0000000000000000000000000000000000000000..d9714254b844419714d6fe84b1f1da09a02402e6 --- /dev/null +++ b/-QuQ--master/config/IBMToken.cfg @@ -0,0 +1,5 @@ +{"url":"https://quantumexperience.ng.bluemix.net/api"} +{"token":"35aea318934a99580a91a7b9d86c87a7b233f04df077a51f1f3a9f14089683e2493fb71d9e91eed4c883f645aa128ae429fd2b7ac7fa26497365a0ac5876a012"} +{"device":"ibmqx2"} +{"shot":"1024"} +{"connectivity":{"ibmqx2":{"0":["1","2"],"1":["2"],"3":["2","4"],"4":["2"]},"ibmqx4":{"1":["0"],"2":["0","1","4"],"3":["2","4"]},"ibmqx5":{"1":["2"],"2":["3"],"3":["4","14"],"5":["4"],"6":["7","11"],"7":["10"],"8":["7"],"9":["8","10"],"11":["10"],"12":["5","11","13"],"13":["4","14"],"15":["0","2","14"]}}} \ No newline at end of file diff --git a/-QuQ--master/config/executeMode.cfg b/-QuQ--master/config/executeMode.cfg new file mode 100644 index 0000000000000000000000000000000000000000..5423cee29adad20f372e33365f2b80d005754053 --- /dev/null +++ b/-QuQ--master/config/executeMode.cfg @@ -0,0 +1,2 @@ +{"executeMode":"simulator"} +{"precision":"4"} \ No newline at end of file diff --git a/-QuQ--master/doc/Liquid-framework.png b/-QuQ--master/doc/Liquid-framework.png new file mode 100644 index 0000000000000000000000000000000000000000..f0f72f19beae5e55ad788eb8508cf606b2f0c1d0 --- /dev/null +++ b/-QuQ--master/doc/Liquid-framework.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6c2d6d1ecef6741a83b7e073ce54e9e5aad25aeeb1c25da4ccdd48a8e7029ccf +size 99352 diff --git a/-QuQ--master/doc/ibm-backend/ibmqx5-backend2017.10.25-2.png b/-QuQ--master/doc/ibm-backend/ibmqx5-backend2017.10.25-2.png new file mode 100644 index 0000000000000000000000000000000000000000..4e9430eb3f1d3ec3c33be8f9c4ef0fcc965add59 --- /dev/null +++ b/-QuQ--master/doc/ibm-backend/ibmqx5-backend2017.10.25-2.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7ccbbf7c6a663eeaacf5048c6cc423a5ebc3b9a7692394382bf3d5955ca7d665 +size 25174 diff --git a/-QuQ--master/doc/ibm-backend/ibmqx5-backend2017.10.25-3.png b/-QuQ--master/doc/ibm-backend/ibmqx5-backend2017.10.25-3.png new file mode 100644 index 0000000000000000000000000000000000000000..f8aee8885f63285565ebce9c704830823f1f23f0 --- /dev/null +++ b/-QuQ--master/doc/ibm-backend/ibmqx5-backend2017.10.25-3.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:df95bb7601d2873a7208b14cf836ed34c7a950d0521be50df04aecfae52c9e77 +size 12152 diff --git a/-QuQ--master/doc/references/High Performance Emulation of Quantum Circuits.pdf b/-QuQ--master/doc/references/High Performance Emulation of Quantum Circuits.pdf new file mode 100644 index 0000000000000000000000000000000000000000..33b491fe0becd93eab39c20ed28ebdc812d3955a --- /dev/null +++ b/-QuQ--master/doc/references/High Performance Emulation of Quantum Circuits.pdf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d8bca63e44a599d89bb6da7049386b99ad417d65722a7ba11c0e95bb6df0fc73 +size 593924 diff --git "a/-QuQ--master/doc/references/Simulating the E\357\254\200ect of Decoherence and Inaccuracies on a Quantum Computer.pdf" "b/-QuQ--master/doc/references/Simulating the E\357\254\200ect of Decoherence and Inaccuracies on a Quantum Computer.pdf" new file mode 100644 index 0000000000000000000000000000000000000000..5f18f271ffb2c57aee9063847e13b538c88cc154 --- /dev/null +++ "b/-QuQ--master/doc/references/Simulating the E\357\254\200ect of Decoherence and Inaccuracies on a Quantum Computer.pdf" @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:50e9ed1a25754c3113ad65ac41743a8ef4acbb14c741ed432b2cd6e88ac1baa4 +size 231018 diff --git a/-QuQ--master/memory-record.txt b/-QuQ--master/memory-record.txt new file mode 100644 index 0000000000000000000000000000000000000000..344258955f4cefd5f29524a9cfca978834b446a9 --- /dev/null +++ b/-QuQ--master/memory-record.txt @@ -0,0 +1,29 @@ +统计内存使用: +声明20个qubit, +将0和1,1和2...13和14进行纠缠,得出内存: +执行前:53866496 +执行后:59154432 +差了5287936bit = 5.0429M + +将0和1...14和15进行纠缠,得出内存: +执行前:53915648 +执行后:63778816 +差了9863168bit = 9.40625M + +将0和1...15和16进行纠缠,得出内存: +执行前:53878784 +执行后:70717440 +差了16838656bit = 16.0586M + +将0和1...16和17进行纠缠,得出内存: +执行前:53878784 +执行后:85184512 +差了3130528bit = 29.85546875M + + + +在simulator模式的执行下,因为最终结果的态可能对应的概率幅的平方和不为1,所以采用helperFunction里面的函数normalize函数将其归一化,这种 +处理方式是否正确 + +测量时采用monte-carlo simulation方法 + diff --git a/-QuQ--master/pic/QuanSim-FrameWork.png b/-QuQ--master/pic/QuanSim-FrameWork.png new file mode 100644 index 0000000000000000000000000000000000000000..7fdd6368968cb29e284a2b192c758ab68335d93b --- /dev/null +++ b/-QuQ--master/pic/QuanSim-FrameWork.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:89a7ef677eabf26dfe43ad35e2ea2b9581af47b47bcdf365b84f7347f4cddb2f +size 52878 diff --git a/-QuQ--master/tools/helperFunction.py b/-QuQ--master/tools/helperFunction.py new file mode 100644 index 0000000000000000000000000000000000000000..97dde2fb2c000a4d558717d7cf8a25267d7c386d --- /dev/null +++ b/-QuQ--master/tools/helperFunction.py @@ -0,0 +1,170 @@ +#!/usr/bin/python3 +#public function is written in this file +import sys +import os +sys.path.append('../baseClass/') + +from Bit import Bit + +#from Circuit import * +from interactCfg import * + +#return a str according to the number of qubits and the postion of 1 +#For example: getCorrespondStr(3,0) = 00000001; (3,1) = 00000010 +def getCorrespondStr(number,position): + strs = bin(int(position)).split('b')[1] + while len(strs) < number: + strs = '0' + strs + return strs + +#suggest use this function to print message +#it can decide the style of output according to the type of the input +def QSprint(data): + from Qubit import Qubit,Qubits + precision = readCfgP() + preStr = '{:.' + str(precision) + 'f}' + types = type(data) + if types == Bit: + print("{\"Type:" + "Bit;") + print(" Value:" + str(data.value) + ";") + if 'c' in data.ids: + print(" Original qubit:" + "None" + ";") + else: + print(" Original qubit:" + str(data.ids) + ";") + print(" ID:" + str(data.ids) +" \"}" ) + + if types == Qubit: + print("{\"Type:" + "Qubit;") + #the amplitude is complex will disturb the format + amplitude = data.getAmp() + coefficient0 = amplitude[0] + coefficient1 = amplitude[1] + if coefficient0.imag == 0: + coefficient0 = coefficient0.real + if coefficient1.imag == 0: + coefficient1 = coefficient1.real + value = preStr.format(coefficient0) + "|0> + " + preStr.format(coefficient1) + "|1>" + print(" Value:" + value + ";") + print(" ID:" + str(data.ids) +" \"}" ) + + if types == Qubits: + print("{\"Type:" + "Qubits;") + print(" The Number of Qubits:" + str(data.number)) + qubitStr = "" + for i in range(0,data.number): + qubitStr += "Q" + str(data[i].ids) + ";" + print(" They are:" + qubitStr ) + value = "" + length = 2**data.number + amplitude = data.getAmp() + for j in range(0,length): + real = amplitude[j].real + imag = amplitude[j].imag + if real == 0 and imag == 0: + continue + elif imag == 0 and real != 0: + value += preStr.format(real) + "|" + getCorrespondStr(data.number,j) + ">" + elif imag != 0 and real == 0: + value += preStr.format(imag) + "|" + getCorrespondStr(data.number,j) + ">" + else: + value += "(" + preStr.format(real) + "+" + preStr.format(imag) + "j)" + "|" + getCorrespondStr(data.number,j) + ">" + if j != (length-1): + value += "+" + print(" Value:" + value +" \"}") + + +#get the info about the function name and the line number +def get_curl_info(): + try: + raise Exception + except: + f = sys.exc_info()[2].tb_frame.f_back + return [f.f_code.co_name, f.f_lineno] + +#sort the qubitList according to the qubit.ids +def quickSortQubit(ql,low,high): + i = low + j = high + if i >= j: + return ql + key = ql[low] + while i < j: + while i < j and ql[j].ids <= key.ids: + j = j-1 + ql[i] = ql[j] + while i < j and ql[i].ids >= key.ids: + i = i+1 + ql[j] = ql[i] + ql[i] = key + quickSortQubit(ql,low,i-1) + quickSortQubit(ql,j+1,high) + return ql + return True + +#judge whether d2 in d1 +def dictInDict(d1,d2): + bools = False + for k in d2: + if k in d1 and d2[k] == d1[k]: + bools = True + else: + bools = False + return bools + +#construct the partitioned matrix +def constructPM(m1,m2): + #use the m1 and m2 as the diagonal element + m1_rows = len(m1) + m1_cols = len(m1[0]) + m2_rows = len(m2) + m2_cols = len(m2[0]) + mNew = [] + mNew_cols = m1_cols * m2_cols + mNew_rows = m1_rows * m2_rows + for i in range(0,m1_rows): + for l in range(0,m2_rows): + tmp = [] + for j in range(0,m1_cols): + for k in range(0,m2_cols): + tmp.append(m1[i][j] * m2[l][k]) + mNew.append(tmp) + return mNew + +#sort the list1 according to the list2 +def adjustOrder(list1:list,list2:list): + for i in range(1,len(list2)): + tmp = i-1 + while tmp >=0: + if list2[tmp] > list2[i]: + list2[i],list2[tmp] = list2[tmp],list2[i] + list1[i],list1[tmp] = list1[tmp],list1[i] + i = tmp + tmp -= 1 + return True + +#judge whether there is repeating element in the list. +#If two elements have the same address, then we say that the two elements are repeating elements. +#if there is repeating elements, then return True; else return False +def repeatElement(lt:list): + for i in range(0,len(lt)): + for j in range(i+1,len(lt)): + if id(lt[i]) == id(lt[j]): + return True + return False + +#create a folder and the parameter "" stands for the name of the folder +def createFolder(name): + tmp = 1 + #create a new folder according to the parameter "name" + while os.path.exists(name) == True: + name += str(tmp) + tmp += 1 + + #the whole result of the experiment is stored in this folder + try: + os.makedirs(name) + except OSError: + info = helperFunction.get_curl_info() + funName = info[0] + line = info[1] + writeErrorMsg("Can't create the new folder '" + self.name + "'!",funName,line) diff --git a/-QuQ--master/tools/interactCfg.py b/-QuQ--master/tools/interactCfg.py new file mode 100644 index 0000000000000000000000000000000000000000..1406c1e7ec3ae423841b9502c1c5c2d3b5758773 --- /dev/null +++ b/-QuQ--master/tools/interactCfg.py @@ -0,0 +1,155 @@ +#!/usr/bin/python3 +#interact with the cfg file +import datetime +import json +import sys +import os +sys.path.append('../baseClass/') +cfgLocation = "../config/" + +#write the error message to LOG when error occurs +def writeErrorMsg(msg,funName,line): + print("Unfortunately, the following errors were happened in QuanSim when running the code:") + funName = "Function Name: "+ str(funName) + "()" + line = "Line: "+ str(line) + print(funName) + print(line) + print(msg) + + #import the Circuit class + from Circuit import Circuit + circuit = Circuit.instance + if circuit == None: + print("there is no circuit instance in the code, please add at least one instance!") + else: + file = open(circuit.urls + "/errorMsg.txt","a") + time = datetime.datetime.now() + errorStr = "Time:" + str(time) + "\r\n" + errorStr += "Error Message: " + errorStr += str(msg) + errorStr += "\r\n" + errorStr += funName + errorStr += "\r\n" + errorStr += line + file.write(errorStr) + file.close + sys.exit(1) + +#read the config file about the executeMode (EM for short) +def readCfgEM(): + try: + EMcfg = cfgLocation + "executeMode.cfg" + confFile = open(EMcfg,"r") + content = confFile.readline() + mode = json.loads(content)['executeMode'] + except IOError as io: + writeErrorMsg(io) + except KeyError as ke: + writeErrorMsg("Key: "+ str(ke) + "doesn't exist in executeMode.cfg, please check the cfg file!") + confFile.close() + return mode + +#read the config file about the output precision (P for short) +#the type of return-value is int +def readCfgP(): + try: + EMcfg = cfgLocation + "executeMode.cfg" + confFile = open(EMcfg,"r") + content = confFile.readline() + content = confFile.readline() + pre = json.loads(content)['precision'] + pre = int(pre) + except IOError as io: + writeErrorMsg(io) + except KeyError as ke: + writeErrorMsg("Key: "+ str(ke) + "doesn't exist in executeMode.cfg, please check the cfg file!") + except TypeError as te: + writeErrorMsg(te) + confFile.close() + return pre + +#read the config file about the assignment error (ER for short) +def readCfgER(ids): + #the error of readout error is the fidelity, and shouldn't be read directly + #it's the cumulative results in average + return 0.0 + + # try: + # ERcfg = cfgLocation + "errorRate.cfg" + # confFile = open(ERcfg,"r") + # content = confFile.readline() + # errorList = json.loads(content)['assignmentError'] + # #our data is equal with IBMqx5, there are only 15qubits; so we only have 15 items + # #if current id is bigger then 15, compute ids%15 + # errorRate = float(errorList[str(ids%15)]) + # except IOError as io: + # writeErrorMsg(io) + # except KeyError as ke: + # writeErrorMsg("Key: "+ str(ke) + "doesn't exist in errorRate.cfg, please check the cfg file!") + # confFile.close() + # return errorRate + +#read the config file about the gate error (GE for short) +#if the para gateType == single, then get the single-qubit gate error according to the qid +#if the para gateType == multi, then get the multi-qubit gate error; +#in the second case, all the qubit have the same error rate +def readCfgGE(gateType:str,qid = None): + if gateType == 'single' and qid == None: + writeErrorMsg("You want to get the single-qubit gate error, but don't give the id of the qubit!") + try: + ERcfg = cfgLocation + "errorRate.cfg" + confFile = open(ERcfg,"r") + content = confFile.readlines() + for line in content: + js = json.loads(line) + if gateType in js.keys(): + if gateType == "single": + errorRate = float(js[gateType][str(qid%15)]) + elif gateType == "multi": + errorRate = float(js[gateType]) + else: + writeErrorMsg("There are only two kinds of gate errors: 'single' or 'multi'; but you gave another one!") + except IOError as io: + writeErrorMsg(io) + except KeyError as ke: + writeErrorMsg("Key: "+ str(ke) + "doesn't exist in errorRate.cfg, please check the cfg file!") + confFile.close() + return errorRate + +#read the config file about the personal message on IBMQX(PM for short) +def readCfgPM(): + result = {} + try: + message = cfgLocation + "IBMToken.cfg" + confFile = open(message,"r") + lines = confFile.readlines() + for line in lines: + pm = json.loads(line) + result = dict(result,**pm) + except IOError as io: + writeErrorMsg(io) + except KeyError as ke: + writeErrorMsg("Key: "+ str(ke) + "doesn't exist in IBMToken.cfg, please check the cfg file!") + except TypeError as te: + writeErrorMsg(te) + confFile.close() + return result + +#read the config file about the existing algorithm(EA for short) +def readCfgEA(): + try: + EAcfg = cfgLocation + "function.cfg" + confFile = open(EAcfg,"r") + content = confFile.readlines() + result = [] + for line in content: + fileName = json.loads(line)['fileName'] + function = json.loads(line)['entryFunction'] + result.append([fileName,function]) + except IOError as io: + writeErrorMsg(io) + except KeyError as ke: + writeErrorMsg("Key: "+ str(ke) + "doesn't exist in function.cfg, please check the cfg file!") + confFile.close() + return result + diff --git a/-QuQ--master/userCode/ExpWrong.py b/-QuQ--master/userCode/ExpWrong.py new file mode 100644 index 0000000000000000000000000000000000000000..595b12cd5d3734bdffe3c49c9e9de49b8ce906f3 --- /dev/null +++ b/-QuQ--master/userCode/ExpWrong.py @@ -0,0 +1,9 @@ +from header import * + +def wrong(): + c = Circuit(True) + q = Qubit() + #the qubit has the same id of q + q_wrong = Qubit(False,0) + M(q) + c.execute(1024) \ No newline at end of file diff --git a/-QuQ--master/userCode/GroverLite.py b/-QuQ--master/userCode/GroverLite.py new file mode 100644 index 0000000000000000000000000000000000000000..b460451c62180a48c7559e7566d1062edac58469 --- /dev/null +++ b/-QuQ--master/userCode/GroverLite.py @@ -0,0 +1,46 @@ +from header import * + +def groverLite(): + totalElement = 4 + targetElement = "11" + #the number of the qubits in theory + N = 3 + c = Circuit() + qList = [] + for i in range(0,N): + q = Qubit() + qList.append(q) + + X(qList[N-1]) + for i in range(0,N): + H(qList[i]) + + #apply the G operator on the qubits + G(qList,targetElement) + + #measure the qubits + for i in range(0,N-1): + qList[i] = M(qList[i]) + + #execute the circuit for 1024 times + c.execute(1024) + +def G(qList:list,target): + vl = [] + for i in range(0,len(target)): + vl.append(int(target[i])) + + with DMif([qList[0],qList[1]],vl) as dmo: + dmo.X(qList[2]) + + for i in range(0,2): + H(qList[i]) + X(qList[i]) + H(qList[1]) + CNOT(qList[0],qList[1]) + H(qList[1]) + for i in range(0,2): + X(qList[i]) + H(qList[i]) + + diff --git a/-QuQ--master/userCode/GroverN=8theory/chart.jpg b/-QuQ--master/userCode/GroverN=8theory/chart.jpg new file mode 100644 index 0000000000000000000000000000000000000000..fbbf15201eea2f2026919c5b555e40724c219bea --- /dev/null +++ b/-QuQ--master/userCode/GroverN=8theory/chart.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d4fa36589132bc75f7ac37c236084357402c1ff94eed2ac127fc09980d7828fe +size 88899 diff --git a/-QuQ--master/userCode/GroverN=8theory/qasm.txt b/-QuQ--master/userCode/GroverN=8theory/qasm.txt new file mode 100644 index 0000000000000000000000000000000000000000..5236482291d6ead9572b8672f2d6443db192afe9 --- /dev/null +++ b/-QuQ--master/userCode/GroverN=8theory/qasm.txt @@ -0,0 +1,133 @@ +OPENQASM 2.0;include "qelib1.inc";qreg q[5];creg c[2]; +h q[0]; +h q[1]; +h q[2]; +h q[3]; +x q[4]; +cx q[1],q[2]; +h q[4]; +tdg q[2]; +h q[4]; +cx q[0],q[2]; +cx q[3],q[4]; +t q[2]; +tdg q[4]; +cx q[1],q[2]; +tdg q[1]; +tdg q[2]; +cx q[0],q[2]; +cx q[0],q[1]; +t q[2]; +tdg q[1]; +h q[2]; +cx q[0],q[1]; +cx q[2],q[4]; +t q[0]; +s q[1]; +t q[4]; +h q[0]; +h q[1]; +cx q[3],q[4]; +x q[0]; +x q[1]; +tdg q[3]; +tdg q[4]; +cx q[2],q[4]; +cx q[2],q[3]; +t q[4]; +tdg q[3]; +h q[4]; +cx q[2],q[3]; +h q[4]; +t q[2]; +s q[3]; +h q[2]; +h q[3]; +cx q[1],q[2]; +x q[3]; +tdg q[2]; +h q[3]; +cx q[0],q[2]; +h q[3]; +t q[2]; +x q[3]; +cx q[1],q[2]; +h q[3]; +tdg q[1]; +tdg q[2]; +cx q[3],q[4]; +cx q[0],q[2]; +tdg q[4]; +cx q[0],q[1]; +t q[2]; +tdg q[1]; +h q[2]; +cx q[0],q[1]; +h q[2]; +t q[0]; +s q[1]; +x q[0]; +x q[1]; +h q[0]; +h q[1]; +cx q[1],q[2]; +tdg q[2]; +cx q[0],q[2]; +t q[2]; +cx q[1],q[2]; +tdg q[1]; +tdg q[2]; +cx q[0],q[2]; +cx q[0],q[1]; +t q[2]; +tdg q[1]; +h q[2]; +cx q[0],q[1]; +cx q[2],q[4]; +t q[0]; +s q[1]; +t q[4]; +h q[0]; +h q[1]; +cx q[3],q[4]; +x q[0]; +x q[1]; +tdg q[3]; +tdg q[4]; +cx q[2],q[4]; +cx q[2],q[3]; +t q[4]; +tdg q[3]; +h q[4]; +cx q[2],q[3]; +t q[2]; +s q[3]; +h q[2]; +h q[3]; +cx q[1],q[2]; +x q[3]; +tdg q[2]; +h q[3]; +cx q[0],q[2]; +h q[3]; +t q[2]; +x q[3]; +cx q[1],q[2]; +h q[3]; +tdg q[1]; +tdg q[2]; +measure q[3] -> c[3]; +cx q[0],q[2]; +cx q[0],q[1]; +t q[2]; +tdg q[1]; +h q[2]; +cx q[0],q[1]; +t q[0]; +s q[1]; +x q[0]; +x q[1]; +h q[0]; +h q[1]; +measure q[0] -> c[0]; +measure q[1] -> c[1]; diff --git a/-QuQ--master/userCode/Test.py b/-QuQ--master/userCode/Test.py new file mode 100644 index 0000000000000000000000000000000000000000..d00a0cc6e9fe26aca123cab6098839e50f7f7a8d --- /dev/null +++ b/-QuQ--master/userCode/Test.py @@ -0,0 +1,70 @@ +from header import * + +def u(): + c = Circuit(True) + q0 = Qubit() + q1 = Qubit() + q2 = Qubit() + q3 = Qubit() + Rx(PI/4,q3) + Rx(PI/4,q3) + Rx(PI/4,q3) + Rx(PI/4,q3) + # with DMif([q0,q1],[1,0]) as dmo: + # dmo.H(q2) + # dmo.CNOT(q2,q3) + # with Qif([q0,q1],[1,0]) as isTrue: + # if isTrue: + # H(q2) + # CNOT(q2,q3) + #M(q2) + M(q3) + c.execute(1024) + # bt = c.beginTime + # bm = c.beginMemory + # sums = 1 + # for i in range(1,2001): + # sums *= i + # time.sleep(0.001) + # c.execute(1) + # et = c.endTime + # em = c.endMemory + # print("娑堣楁椂闂达細%d S"%(et-bt).total_seconds()) + # print("鍗犵敤鍐呭瓨锛%d bit"%(em-bm)) + #c.execute(1) + # q = Qubit() + # qList = [] + # for i in range(0,2): + # qList.append(Qubit()) + # #Rx(PI,qList[0]) + # #Rx(PI,qList[0]) + # #X(q) + # #QSprint(qList[0]) + # #X(q) + # #Toffoli(q,qList[0],qList[1]) + # #CNOT(qList[0],qList[1]) + # with Mif([qList[0],qList[1]],[0,0]) as mo: + # mo.X(q) + # #mo.H(qList[1]) + # #mo.CNOT(q,qList[1]) + # # mo.CNOT(qList[2],qList[1]) + # q1 = Qubit() + # q2 = Qubit() + # Rx(PI,q2) + # #print(c.qubitExecuteListOD) + # #Rx(PI/2,q) + # with DMif([q1,q2],[0,1]) as dmo: + # dmo.H(q) + # #dmo.H(qList[1]) + # #q = dmo.Ry(PI,q)[-1] + # #q = dmo.Rz(-PI/2,q)[-1] + # # with DMif([qList[0],qList[1]],[1,0]) as dmo: + # # dmo.H(q) + # #M(qList[1]) + # #QSprint(q) + # #QSprint(q.entanglement) + # #M(q) + # #QSprint(q) + # M(q) + # #M(qList[0]) + #c.execute(1024) \ No newline at end of file diff --git a/-QuQ--master/userCode/header.py b/-QuQ--master/userCode/header.py new file mode 100644 index 0000000000000000000000000000000000000000..94ba5aefcc864576c50b06759f30437361e4c166 --- /dev/null +++ b/-QuQ--master/userCode/header.py @@ -0,0 +1,15 @@ +################################################################ +#Any code file in the floder "userCode" should import this file +################################################################ + +import sys +sys.path.append('../baseClass/') +sys.path.append('../tools/') +from Bit import Bit +from Qubit import * +from helperFunction import * +from Circuit import Circuit +from Gate import * +from ControlFlow import * +#from IBMQX import * +PI = math.pi \ No newline at end of file diff --git a/.gitattributes b/.gitattributes index 1ef325f1b111266a6b26e0196871bd78baa8c2f3..f1b0d909316d6ee0fa1969592d27ce84d7b5c208 100644 --- a/.gitattributes +++ b/.gitattributes @@ -57,3 +57,5 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text # Video files - compressed *.mp4 filter=lfs diff=lfs merge=lfs -text *.webm filter=lfs diff=lfs merge=lfs -text +-QuQ--master/doc/references/Simulating[[:space:]]the[[:space:]]E铿ect[[:space:]]of[[:space:]]Decoherence[[:space:]]and[[:space:]]Inaccuracies[[:space:]]on[[:space:]]a[[:space:]]Quantum[[:space:]]Computer.pdf filter=lfs diff=lfs merge=lfs -text +-QuQ--master/doc/references/High[[:space:]]Performance[[:space:]]Emulation[[:space:]]of[[:space:]]Quantum[[:space:]]Circuits.pdf filter=lfs diff=lfs merge=lfs -text diff --git a/0617-audio_stream-master/.pipreqs/requirements_pipreqs.txt b/0617-audio_stream-master/.pipreqs/requirements_pipreqs.txt new file mode 100644 index 0000000000000000000000000000000000000000..3f425b06fbceb9aec59089d163ab570d184962e8 --- /dev/null +++ b/0617-audio_stream-master/.pipreqs/requirements_pipreqs.txt @@ -0,0 +1,6 @@ +matplotlib==3.10.1 +numpy==2.2.4 +Pillow==11.1.0 +scipy==1.15.2 +torch==2.1.0 +torchvision==0.16.0+cu121 diff --git a/0617-audio_stream-master/audio_process.py b/0617-audio_stream-master/audio_process.py new file mode 100644 index 0000000000000000000000000000000000000000..7ee011f1d70eb51f1a1e5d6df478d83e35467723 --- /dev/null +++ b/0617-audio_stream-master/audio_process.py @@ -0,0 +1,16 @@ +import os +import torch +from hyper import * +from PIL import Image +import torchvision.transforms.functional as F + + +def load_single_sp_gt(sp_name, gt_name): + audio = Image.open(sp_name).convert('RGB') + audio_data = F.to_tensor(audio) + audio_data = F.normalize(audio_data, MEAN, STD) + + gt = Image.open(gt_name).convert('L') + gt_data = F.to_tensor(gt) + + return audio_data, gt_data diff --git a/0617-audio_stream-master/dataset.py b/0617-audio_stream-master/dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..1440b51e28b5175aa14969c79165c5fcb647fa72 --- /dev/null +++ b/0617-audio_stream-master/dataset.py @@ -0,0 +1,53 @@ +import torch.utils.data as data +from audio_process import * +from mean_std import * + + +class LoadDataset(data.Dataset): + def __init__(self, root_folder): + self.root_folder = root_folder + self.specs = [] + self.gt = [] + + specs_path = self.root_folder.split('frames')[0] + 'specs' + self.root_folder.split('frames')[1] + print("Specs Root : ", specs_path, "\n") + + self.specs = [os.path.join(specs_path, f) for f in os.listdir(specs_path) if f.endswith('.jpg')] + self.gt = [os.path.join(self.root_folder, f) for f in os.listdir(self.root_folder) if f.endswith('.jpg')] + + self.specs.sort() + self.gt.sort() + + def __len__(self): + return len(self.specs) + + def __getitem__(self, item): + sp_name = self.specs[item] + gt_name = self.gt[item] + + audio_data, gt_data = load_single_sp_gt(sp_name, gt_name) + + return audio_data, gt_data + + +class LoadTestData: + def __init__(self, test_root): + # print(test_root, specs_root) + self.frames = [test_root + f for f in os.listdir(test_root) if f.endswith('.jpg')] + self.frames = sorted(self.frames) + self.size = len(self.frames) + self.index = 0 + + def load_data(self): + frame = self.data_loader_frames(self.frames[self.index]) + name = self.frames[self.index].split('/')[-1] + self.index += 1 + + return frame, name, self.index + + def data_loader_frames(self, name): + audio = Image.open(name).convert('RGB') + # convert a PIL image to tensor (HWC) in range [0,255] to a torch.Tensor(CHW) in the range [0.0,1.0] + audio_data = F.to_tensor(audio) + + return audio_data diff --git a/0617-audio_stream-master/model/CPD_models.py b/0617-audio_stream-master/model/CPD_models.py new file mode 100644 index 0000000000000000000000000000000000000000..5f1f739b7fca7b0313e104d77159971540172070 --- /dev/null +++ b/0617-audio_stream-master/model/CPD_models.py @@ -0,0 +1,256 @@ +import torch +import torch.nn as nn +import torchvision +from hyper import * +from model.HolisticAttention import HA +from model.ResNe3D import resnet18 +from model.ResNet_18 import ResNet2_18 +from model.vgg import B2_VGG +from model.v_a_con import * + + +class RFB(nn.Module): + def __init__(self, in_channel, out_channel): + super(RFB, self).__init__() + self.relu = nn.ReLU(True) + self.branch0 = nn.Sequential( + nn.Conv2d(in_channel, out_channel, 1), + ) + self.branch1 = nn.Sequential( + nn.Conv2d(in_channel, out_channel, 1), + nn.Conv2d(out_channel, out_channel, kernel_size=(1, 3), padding=(0, 1)), + nn.Conv2d(out_channel, out_channel, kernel_size=(3, 1), padding=(1, 0)), + nn.Conv2d(out_channel, out_channel, 3, padding=3, dilation=3) + ) + self.branch2 = nn.Sequential( + nn.Conv2d(in_channel, out_channel, 1), + nn.Conv2d(out_channel, out_channel, kernel_size=(1, 5), padding=(0, 2)), + nn.Conv2d(out_channel, out_channel, kernel_size=(5, 1), padding=(2, 0)), + nn.Conv2d(out_channel, out_channel, 3, padding=5, dilation=5) + ) + self.branch3 = nn.Sequential( + nn.Conv2d(in_channel, out_channel, 1), + nn.Conv2d(out_channel, out_channel, kernel_size=(1, 7), padding=(0, 3)), + nn.Conv2d(out_channel, out_channel, kernel_size=(7, 1), padding=(3, 0)), + nn.Conv2d(out_channel, out_channel, 3, padding=7, dilation=7) + ) + self.conv_cat = nn.Conv2d(4 * out_channel, out_channel, 3, padding=1) + self.conv_res = nn.Conv2d(in_channel, out_channel, 1) + + for m in self.modules(): + if isinstance(m, nn.Conv2d): + m.weight.data.normal_(std=0.01) + m.bias.data.fill_(0) + + def forward(self, x): + x0 = self.branch0(x) + x1 = self.branch1(x) + x2 = self.branch2(x) + x3 = self.branch3(x) + + x_cat = torch.cat((x0, x1, x2, x3), 1) + x_cat = self.conv_cat(x_cat) + + x = self.relu(x_cat + self.conv_res(x)) + return x + + +class aggregation(nn.Module): + def __init__(self, channel): + super(aggregation, self).__init__() + self.relu = nn.ReLU(True) + + self.upsample = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=True) + self.conv_upsample1 = nn.Conv2d(channel, channel, 3, padding=1) + self.conv_upsample2 = nn.Conv2d(channel, channel, 3, padding=1) + self.conv_upsample3 = nn.Conv2d(channel, channel, 3, padding=1) + self.conv_upsample4 = nn.Conv2d(channel, channel, 3, padding=1) + self.conv_upsample5 = nn.Conv2d(2 * channel, 2 * channel, 3, padding=1) + + self.conv_concat2 = nn.Conv2d(2 * channel, 2 * channel, 3, padding=1) + self.conv_concat3 = nn.Conv2d(3 * channel, 3 * channel, 3, padding=1) + self.conv4 = nn.Conv2d(3 * channel, 3 * channel, 3, padding=1) + self.conv5 = nn.Conv2d(3 * channel, 1, 1) + + for m in self.modules(): + if isinstance(m, nn.Conv2d): + m.weight.data.normal_(std=0.01) + m.bias.data.fill_(0) + + def forward(self, x1, x2, x3): + # x1: 1/16 x2: 1/8 x3: 1/4 + x1_1 = x1 + + x2_1 = self.conv_upsample1(self.upsample(x1)) * x2 + + x3_1 = self.conv_upsample2(self.upsample(self.upsample(x1))) \ + * self.conv_upsample3(self.upsample(x2)) * x3 + + x2_2 = torch.cat((x2_1, self.conv_upsample4(self.upsample(x1_1))), 1) + + x2_2 = self.conv_concat2(x2_2) + + x3_2 = torch.cat((x3_1, self.conv_upsample5(self.upsample(x2_2))), 1) + + x3_2 = self.conv_concat3(x3_2) + + x = self.conv4(x3_2) + x = self.conv5(x) + + return x + + +class CPD_VGG(nn.Module): + def __init__(self, channel=32): + super(CPD_VGG, self).__init__() + self.vgg = B2_VGG() + self.rfb3_1 = RFB(256, channel) + self.rfb4_1 = RFB(512, channel) + self.rfb5_1 = RFB(512, channel) + self.agg1 = aggregation(channel) + + self.rfb3_2 = RFB(256, channel) + self.rfb4_2 = RFB(512, channel) + self.rfb5_2 = RFB(512, channel) + self.agg2 = aggregation(channel) + + self.HA = HA() + self.upsample = nn.Upsample(scale_factor=4, mode='bilinear', align_corners=False) + + def forward(self, x, y): + x1 = self.vgg.conv1(x) + x2 = self.vgg.conv2(x1) + x3 = self.vgg.conv3(x2) + x3_1 = x3 + + x4_1 = self.vgg.conv4_1(x3_1) + x5_1 = self.vgg.conv5_1(x4_1) + + ''' + Audio Stream + ''' + y1 = self.spec_vgg.conv1(y) + y2 = self.spec_vgg.conv2(y1) + y3 = self.spec_vgg.conv3(y2) + y3_1 = y3 + + y4_1 = self.spec_vgg.conv4_1(y3_1) + y5_1 = self.spec_vgg.conv5_1(y4_1) + ''' + video stream and audio stream concentration + ''' + print("CPD video : ", x3_1.shape, x4_1.shape, x5_1.shape) + print("CPD audio : ", y3_1.shape, y4_1.shape, y5_1.shape) + exit(0) + mix3 = self.v_a_con(x3_1, y3_1) + mix4 = self.v_a_con(x4_1, y4_1) + mix5 = self.v_a_con(x5_1, y5_1) + x3_1 = self.v_a_con.conv_3(mix3) + x4_1 = self.v_a_con.conv_4(mix4) + x5_1 = self.v_a_con.conv_5(mix5) + ''' + print('Conca : ', mix3.shape, mix4.shape, mix5.shape) + print('Conca : ', x3_1.shape, x4_1.shape, x5_1.shape) + exit(0) + ''' + x3_1 = self.rfb3_1(x3_1) + x4_1 = self.rfb4_1(x4_1) + x5_1 = self.rfb5_1(x5_1) + + attention = self.agg1(x5_1, x4_1, x3_1) + + x3_2 = self.HA(attention.sigmoid(), x3) + x4_2 = self.vgg.conv4_2(x3_2) + x5_2 = self.vgg.conv5_2(x4_2) + x3_2 = self.rfb3_2(x3_2) + x4_2 = self.rfb4_2(x4_2) + x5_2 = self.rfb5_2(x5_2) + detection = self.agg2(x5_2, x4_2, x3_2) + + return self.upsample(attention), self.upsample(detection) + + +class CPD_3DResNet(nn.Module): + def __init__(self, channel=32): + super(CPD_3DResNet, self).__init__() + # self.video_branch = resnet18(shortcut_type='A', sample_size=112, sample_duration=16, last_fc=False, + # last_pool=False) + # self.audio_branch = resnet18(shortcut_type='A', sample_size=64, sample_duration=16, num_classes=12, + # last_fc=False, last_pool=True) + # self.audio_branch = ResNet2_18() + self.audio_branch = torchvision.models.resnet18(pretrained=False) + + self.v_a_con = Video_Audio_Con() + + self.vgg = B2_VGG() + self.rfb3_1 = RFB(256, channel) + self.rfb4_1 = RFB(512, channel) + self.rfb5_1 = RFB(512, channel) + self.agg1 = aggregation(channel) + + self.rfb3_2 = RFB(256, channel) + self.rfb4_2 = RFB(512, channel) + self.rfb5_2 = RFB(512, channel) + self.agg2 = aggregation(channel) + + self.HA = HA() + + self.upsample_a1 = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=False) + self.upsample_a2 = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=False) + self.upsample_a3 = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=False) + ''' + ''' + self.upsample = nn.Upsample(scale_factor=4, mode='bilinear', align_corners=False) + + def forward(self, a): + # f_num = 3, [bs, 128, 32, 40] [bs, 256, 16, 20] [bs, 512, 8, 10] + # v1, v2, v3 = self.video_branch(v) + a1, a2, a3 = self.audio_branch(a) + + ''' + a1 = self.v_a_con_audio.upsample_a1(a1) + detection = self.v_a_con_audio.conv_last(a1) + ''' + ''' + print(a1.shape, a2.shape, a3.shape) + exit(0) + ''' + + ''' + a1 = torch.squeeze(a1, dim=2) + a1 = self.v_a_con_10.upsample_a1(a1) + detection = self.v_a_con_10.conv_last(a1) + ''' + + a1 = self.upsample_a1(a1) + a2 = self.upsample_a2(a2) + a3 = self.upsample_a3(a3) + + x3_1 = self.v_a_con.conv_3(a1) + x4_1 = self.v_a_con.conv_4(a2) + x5_1 = self.v_a_con.conv_5(a3) + + xx = x3_1 + # print(x3_1.shape, x4_1.shape, x5_1.shape) + + x3_1 = self.rfb3_1(x3_1) + x4_1 = self.rfb4_1(x4_1) + x5_1 = self.rfb5_1(x5_1) + # print(x3_1.shape, x4_1.shape, x5_1.shape) + + attention = self.agg1(x5_1, x4_1, x3_1) + + x3_2 = self.HA(attention.sigmoid(), xx) + x4_2 = self.vgg.conv4_2(x3_2) + x5_2 = self.vgg.conv5_2(x4_2) + # print(x3_2.shape, x4_2.shape, x5_2.shape) + # exit(0) + + x3_2 = self.rfb3_2(x3_2) + x4_2 = self.rfb4_2(x4_2) + x5_2 = self.rfb5_2(x5_2) + detection = self.agg2(x5_2, x4_2, x3_2) + + ''' + ''' + return self.upsample(detection) diff --git a/0617-audio_stream-master/model/HolisticAttention.py b/0617-audio_stream-master/model/HolisticAttention.py new file mode 100644 index 0000000000000000000000000000000000000000..389464a32b2ad5cef675a395bb53453b94c8fa42 --- /dev/null +++ b/0617-audio_stream-master/model/HolisticAttention.py @@ -0,0 +1,40 @@ +import torch +import torch.nn.functional as F +import torch.nn as nn +from torch.nn.parameter import Parameter + +import numpy as np +import scipy.stats as st + + +def gkern(kernlen=16, nsig=3): + interval = (2*nsig+1.)/kernlen + x = np.linspace(-nsig-interval/2., nsig+interval/2., kernlen+1) + kern1d = np.diff(st.norm.cdf(x)) + kernel_raw = np.sqrt(np.outer(kern1d, kern1d)) + kernel = kernel_raw/kernel_raw.sum() + return kernel + + +def min_max_norm(in_): + max_ = in_.max(3)[0].max(2)[0].unsqueeze(2).unsqueeze(3).expand_as(in_) + min_ = in_.min(3)[0].min(2)[0].unsqueeze(2).unsqueeze(3).expand_as(in_) + in_ = in_ - min_ + return in_.div(max_-min_+1e-8) + + +class HA(nn.Module): + # holistic attention module + def __init__(self): + super(HA, self).__init__() + gaussian_kernel = np.float32(gkern(31, 4)) + gaussian_kernel = gaussian_kernel[np.newaxis, np.newaxis, ...] + self.gaussian_kernel = Parameter(torch.from_numpy(gaussian_kernel)) + + def forward(self, attention, x): + + soft_attention = F.conv2d(attention, self.gaussian_kernel, padding=15) + soft_attention = min_max_norm(soft_attention) + x = torch.mul(x, soft_attention.max(attention)) + + return x diff --git a/0617-audio_stream-master/model/vgg.py b/0617-audio_stream-master/model/vgg.py new file mode 100644 index 0000000000000000000000000000000000000000..5d674b2a820dd8d2fe81f9dd3cea401cb188121d --- /dev/null +++ b/0617-audio_stream-master/model/vgg.py @@ -0,0 +1,130 @@ +import torch.nn as nn + + +class B2_VGG(nn.Module): + # VGG16 with two branches + # pooling layer at the front of block + def __init__(self): + super(B2_VGG, self).__init__() + conv1 = nn.Sequential() + conv1.add_module('conv1_1', nn.Conv2d(3, 64, 3, 1, 1)) + conv1.add_module('relu1_1', nn.ReLU(inplace=True)) + conv1.add_module('conv1_2', nn.Conv2d(64, 64, 3, 1, 1)) + conv1.add_module('relu1_2', nn.ReLU(inplace=True)) + + self.conv1 = conv1 + conv2 = nn.Sequential() + conv2.add_module('pool1', nn.AvgPool2d(2, stride=2)) + conv2.add_module('conv2_1', nn.Conv2d(64, 128, 3, 1, 1)) + conv2.add_module('relu2_1', nn.ReLU()) + conv2.add_module('conv2_2', nn.Conv2d(128, 128, 3, 1, 1)) + conv2.add_module('relu2_2', nn.ReLU()) + self.conv2 = conv2 + + conv3 = nn.Sequential() + conv3.add_module('pool2', nn.AvgPool2d(2, stride=2)) + conv3.add_module('conv3_1', nn.Conv2d(128, 256, 3, 1, 1)) + conv3.add_module('relu3_1', nn.ReLU()) + conv3.add_module('conv3_2', nn.Conv2d(256, 256, 3, 1, 1)) + conv3.add_module('relu3_2', nn.ReLU()) + conv3.add_module('conv3_3', nn.Conv2d(256, 256, 3, 1, 1)) + conv3.add_module('relu3_3', nn.ReLU()) + self.conv3 = conv3 + + conv4_1 = nn.Sequential() + conv4_1.add_module('pool3_1', nn.AvgPool2d(2, stride=2)) + conv4_1.add_module('conv4_1_1', nn.Conv2d(256, 512, 3, 1, 1)) + conv4_1.add_module('relu4_1_1', nn.ReLU()) + conv4_1.add_module('conv4_2_1', nn.Conv2d(512, 512, 3, 1, 1)) + conv4_1.add_module('relu4_2_1', nn.ReLU()) + conv4_1.add_module('conv4_3_1', nn.Conv2d(512, 512, 3, 1, 1)) + conv4_1.add_module('relu4_3_1', nn.ReLU()) + self.conv4_1 = conv4_1 + + conv5_1 = nn.Sequential() + conv5_1.add_module('pool4_1', nn.AvgPool2d(2, stride=2)) + conv5_1.add_module('conv5_1_1', nn.Conv2d(512, 512, 3, 1, 1)) + conv5_1.add_module('relu5_1_1', nn.ReLU()) + conv5_1.add_module('conv5_2_1', nn.Conv2d(512, 512, 3, 1, 1)) + conv5_1.add_module('relu5_2_1', nn.ReLU()) + conv5_1.add_module('conv5_3_1', nn.Conv2d(512, 512, 3, 1, 1)) + conv5_1.add_module('relu5_3_1', nn.ReLU()) + self.conv5_1 = conv5_1 + + conv4_2 = nn.Sequential() + conv4_2.add_module('pool3_2', nn.AvgPool2d(2, stride=2)) + conv4_2.add_module('conv4_1_2', nn.Conv2d(256, 512, 3, 1, 1)) + conv4_2.add_module('relu4_1_2', nn.ReLU()) + conv4_2.add_module('conv4_2_2', nn.Conv2d(512, 512, 3, 1, 1)) + conv4_2.add_module('relu4_2_2', nn.ReLU()) + conv4_2.add_module('conv4_3_2', nn.Conv2d(512, 512, 3, 1, 1)) + conv4_2.add_module('relu4_3_2', nn.ReLU()) + self.conv4_2 = conv4_2 + + conv5_2 = nn.Sequential() + conv5_2.add_module('pool4_2', nn.AvgPool2d(2, stride=2)) + conv5_2.add_module('conv5_1_2', nn.Conv2d(512, 512, 3, 1, 1)) + conv5_2.add_module('relu5_1_2', nn.ReLU()) + conv5_2.add_module('conv5_2_2', nn.Conv2d(512, 512, 3, 1, 1)) + conv5_2.add_module('relu5_2_2', nn.ReLU()) + conv5_2.add_module('conv5_3_2', nn.Conv2d(512, 512, 3, 1, 1)) + conv5_2.add_module('relu5_3_2', nn.ReLU()) + self.conv5_2 = conv5_2 + + # pre_train = torch.load('~/.torch/models/vgg16-397923af.pth') + # pre_train = torch.load('pre-trained/vgg16-397923af.pth') + # self._initialize_weights(pre_train) + print("\n===== This is VGG !=====\n") + + def forward(self, x): + x = self.conv1(x) + x = self.conv2(x) + x = self.conv3(x) + x1 = self.conv4_1(x) + x1 = self.conv5_1(x1) + x2 = self.conv4_2(x) + x2 = self.conv5_2(x2) + return x1, x2 + + def _initialize_weights(self, pre_train): + keys = pre_train.keys() + keys=list(pre_train.keys()) + self.conv1.conv1_1.weight.data.copy_(pre_train[keys[0]]) + self.conv1.conv1_2.weight.data.copy_(pre_train[keys[2]]) + self.conv2.conv2_1.weight.data.copy_(pre_train[keys[4]]) + self.conv2.conv2_2.weight.data.copy_(pre_train[keys[6]]) + self.conv3.conv3_1.weight.data.copy_(pre_train[keys[8]]) + self.conv3.conv3_2.weight.data.copy_(pre_train[keys[10]]) + self.conv3.conv3_3.weight.data.copy_(pre_train[keys[12]]) + self.conv4_1.conv4_1_1.weight.data.copy_(pre_train[keys[14]]) + self.conv4_1.conv4_2_1.weight.data.copy_(pre_train[keys[16]]) + self.conv4_1.conv4_3_1.weight.data.copy_(pre_train[keys[18]]) + self.conv5_1.conv5_1_1.weight.data.copy_(pre_train[keys[20]]) + self.conv5_1.conv5_2_1.weight.data.copy_(pre_train[keys[22]]) + self.conv5_1.conv5_3_1.weight.data.copy_(pre_train[keys[24]]) + self.conv4_2.conv4_1_2.weight.data.copy_(pre_train[keys[14]]) + self.conv4_2.conv4_2_2.weight.data.copy_(pre_train[keys[16]]) + self.conv4_2.conv4_3_2.weight.data.copy_(pre_train[keys[18]]) + self.conv5_2.conv5_1_2.weight.data.copy_(pre_train[keys[20]]) + self.conv5_2.conv5_2_2.weight.data.copy_(pre_train[keys[22]]) + self.conv5_2.conv5_3_2.weight.data.copy_(pre_train[keys[24]]) + + self.conv1.conv1_1.bias.data.copy_(pre_train[keys[1]]) + self.conv1.conv1_2.bias.data.copy_(pre_train[keys[3]]) + self.conv2.conv2_1.bias.data.copy_(pre_train[keys[5]]) + self.conv2.conv2_2.bias.data.copy_(pre_train[keys[7]]) + self.conv3.conv3_1.bias.data.copy_(pre_train[keys[9]]) + self.conv3.conv3_2.bias.data.copy_(pre_train[keys[11]]) + self.conv3.conv3_3.bias.data.copy_(pre_train[keys[13]]) + self.conv4_1.conv4_1_1.bias.data.copy_(pre_train[keys[15]]) + self.conv4_1.conv4_2_1.bias.data.copy_(pre_train[keys[17]]) + self.conv4_1.conv4_3_1.bias.data.copy_(pre_train[keys[19]]) + self.conv5_1.conv5_1_1.bias.data.copy_(pre_train[keys[21]]) + self.conv5_1.conv5_2_1.bias.data.copy_(pre_train[keys[23]]) + self.conv5_1.conv5_3_1.bias.data.copy_(pre_train[keys[25]]) + self.conv4_2.conv4_1_2.bias.data.copy_(pre_train[keys[15]]) + self.conv4_2.conv4_2_2.bias.data.copy_(pre_train[keys[17]]) + self.conv4_2.conv4_3_2.bias.data.copy_(pre_train[keys[19]]) + self.conv5_2.conv5_1_2.bias.data.copy_(pre_train[keys[21]]) + self.conv5_2.conv5_2_2.bias.data.copy_(pre_train[keys[23]]) + self.conv5_2.conv5_3_2.bias.data.copy_(pre_train[keys[25]]) diff --git a/0617-audio_stream-master/train.py b/0617-audio_stream-master/train.py new file mode 100644 index 0000000000000000000000000000000000000000..d81be05613aac5150bb68566e3f4738f03add9da --- /dev/null +++ b/0617-audio_stream-master/train.py @@ -0,0 +1,151 @@ +import os +import matplotlib.pyplot as plt +import torch +import numpy as np +from torch.autograd import Variable +from torch.utils.data import DataLoader +from dataset import LoadDataset +from hyper import * +from model.CPD_models import CPD_3DResNet + +torch.cuda.set_device(0) + + +class Train(object): + def __init__(self): + super(Train, self).__init__() + self.train_list = [os.path.join(train_data_path, p) for p in os.listdir(train_data_path)] + self.model = CPD_3DResNet() + self.optimizer = torch.optim.Adam(self.model.parameters(), lr=lr) + self.optimizer_name = str(self.optimizer).split(' ')[0] + self.func_name = str(obj_func).split('()')[0] + self.model = self.model.cuda() + self.loss_dict = [] + self.lr = lr + # self.model.load_state_dict(torch.load(checkpoint_load)) + + save_model = torch.load(checkpoint_load) + # save_model = torch.load(checkpoint_load)['state_dict'] + now_model = self.model.state_dict() + state_dict = {k: v for k, v in save_model.items() if k in now_model.keys()} + now_model.update(state_dict) + self.model.load_state_dict(now_model) + ''' + dict_name = list(state_dict) + for i1, p1 in enumerate(dict_name): + print(i1, p1) + + exit(0) + + f = 0 + # 329 + for name, para in self.model.named_parameters(): + f += 1 + self.flag = [1 for x in range(0, f)] + + ff = 0 + for name, para in self.model.named_parameters(): + for i1, p1 in enumerate(dict_name): + if name == p1: + ff = i1 + self.flag[ff] = 0 + # print(i1, name) + # exit(0) + ''' + + print("\n================\nPre-Model setup OK !\n================") + # self.checkpoint_save = 'No_Pretrained' + torch.cuda.empty_cache() + self.checkpoint_save = checkpoint_save + 'cpd_' + now[5:7] + now[8:10] + + def train(self): + # 鏂板缓淇濆瓨 checkpoint 鐨勬枃浠跺す + if not os.path.exists(self.checkpoint_save): + os.makedirs(self.checkpoint_save) + + for epoch in range(epochs): + print("=====This is Epoch =====", epoch) + ''' + if epoch < 2: + for idx, p in enumerate(self.model.parameters()): + if self.flag[idx] == 0: + p.requires_grad = False + else: + for idx, p in enumerate(self.model.parameters()): + p.requires_grad = True + + fixed = 1 + ''' + + if epoch % decay == 0: + for param_group in self.optimizer.param_groups: + param_group['lr'] = self.lr * 0.1 + self.lr = param_group['lr'] + print("learning rate : {}".format(self.optimizer.state_dict()['param_groups'][0]['lr'])) + learning_rate = str(self.optimizer.state_dict()['param_groups'][0]['lr']) + + dir_num = 0 + + for dir in self.train_list: + i = 0 + train_set = LoadDataset(dir) + train_loader = DataLoader(train_set, batch_size=batch_size, + num_workers=0, shuffle=True) + + for idx, train_data in enumerate(train_loader): + audio, gt = train_data + # print('Train : ', audio.shape, gt.shape) + # exit(0) + # torch.Size([bs, 3, f_num, 256, 320]) + # torch.Size([bs, 3, f_num, 256, 320]) + # torch.Size([bs, 1, 256, 320]) + + # image = Variable(image).cuda() + audio = Variable(audio).cuda() + gt = Variable(gt).cuda() + + det = self.model(audio) + # print('Result : ', det.shape, gt.shape) + # exit(0) + + # loss1 = obj_func(att, gt) + loss2 = obj_func(det, gt) + loss = loss2 + + self.optimizer.zero_grad() + loss.backward() + self.optimizer.step() + self.loss_dict.append(loss.item()) + + i += 1 + + print('Epoch: [{}], Root_folder: {}, Frames: {}, Enumerate: {}\n=====Loss: {:.6f}=====\n'.format( + epoch, dir, len(train_set), i, loss.item())) + ''' + dir_num += 1 + if dir_num == 500: + break + ''' + if epoch % save_hop == 0: + torch.save(self.model.state_dict(), + os.path.join(self.checkpoint_save, 'model_%s_%s_%s_%d_%s_%d.pth' % (checkpoint_name, + self.optimizer_name, + learning_rate, + batch_size, + self.func_name, + epoch))) + + end_time = str(datetime.now())[11:13] + str(datetime.now())[14:16] + save_name = './charts/' + self.optimizer_name + '_' + str(lr) + '_' + self.func_name + '_' + end_time + '.png' + plt.title(self.optimizer_name + '_' + str(lr) + '_' + str(epochs) + '_' + str(decay) + '_' + str(fixed) + end_time) + plt.xlabel('batch') + plt.ylabel('loss') + + plt.plot(self.loss_dict) + plt.savefig(save_name) + plt.show() + + +if __name__ == '__main__': + t = Train() + t.train() diff --git a/0621_test-master/django_app/config/settings.py b/0621_test-master/django_app/config/settings.py new file mode 100644 index 0000000000000000000000000000000000000000..31b96db43253baeeb14bd5816f5fc78dc4cd43ad --- /dev/null +++ b/0621_test-master/django_app/config/settings.py @@ -0,0 +1,127 @@ +""" +Django settings for test_project project. + +Generated by 'django-admin startproject' using Django 1.11.2. + +For more information on this file, see +https://docs.djangoproject.com/en/1.11/topics/settings/ + +For the full list of settings and their values, see +https://docs.djangoproject.com/en/1.11/ref/settings/ +""" + +import os + +# Build paths inside the project like this: os.path.join(BASE_DIR, ...) +BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +TEMPLATES_DIR = os.path.join(BASE_DIR, 'templates') + + +# Quick-start development settings - unsuitable for production +# See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/ + +# SECURITY WARNING: keep the secret key used in production secret! +SECRET_KEY = 'v^72um0=i317_-3&g^1q&!9e)wcit&*mlt_ejz#p03_vu=9p1s' + +# SECURITY WARNING: don't run with debug turned on in production! +DEBUG = True + +ALLOWED_HOSTS = [] + + +# Application definition + +INSTALLED_APPS = [ + 'django.contrib.admin', + 'django.contrib.auth', + 'django.contrib.contenttypes', + 'django.contrib.sessions', + 'django.contrib.messages', + 'django.contrib.staticfiles', + + 'django_extensions', + + 'post' +] + +MIDDLEWARE = [ + 'django.middleware.security.SecurityMiddleware', + 'django.contrib.sessions.middleware.SessionMiddleware', + 'django.middleware.common.CommonMiddleware', + 'django.middleware.csrf.CsrfViewMiddleware', + 'django.contrib.auth.middleware.AuthenticationMiddleware', + 'django.contrib.messages.middleware.MessageMiddleware', + 'django.middleware.clickjacking.XFrameOptionsMiddleware', +] + +ROOT_URLCONF = 'config.urls' + +TEMPLATES = [ + { + 'BACKEND': 'django.template.backends.django.DjangoTemplates', + 'DIRS': [ + TEMPLATES_DIR + ], + 'APP_DIRS': True, + 'OPTIONS': { + 'context_processors': [ + 'django.template.context_processors.debug', + 'django.template.context_processors.request', + 'django.contrib.auth.context_processors.auth', + 'django.contrib.messages.context_processors.messages', + ], + }, + }, +] + +WSGI_APPLICATION = 'config.wsgi.application' + + +# Database +# https://docs.djangoproject.com/en/1.11/ref/settings/#databases + +DATABASES = { + 'default': { + 'ENGINE': 'django.db.backends.sqlite3', + 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), + } +} + + +# Password validation +# https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators + +AUTH_PASSWORD_VALIDATORS = [ + { + 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', + }, + { + 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', + }, + { + 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', + }, + { + 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', + }, +] + + +# Internationalization +# https://docs.djangoproject.com/en/1.11/topics/i18n/ + +LANGUAGE_CODE = 'en-us' + +TIME_ZONE = 'UTC' + +USE_I18N = True + +USE_L10N = True + +USE_TZ = True + + +# Static files (CSS, JavaScript, Images) +# https://docs.djangoproject.com/en/1.11/howto/static-files/ + +STATIC_URL = '/static/' diff --git a/0621_test-master/django_app/config/wsgi.py b/0621_test-master/django_app/config/wsgi.py new file mode 100644 index 0000000000000000000000000000000000000000..0896cffb605c571a3ac7f604161d37d32fc37045 --- /dev/null +++ b/0621_test-master/django_app/config/wsgi.py @@ -0,0 +1,16 @@ +""" +WSGI config for test_project project. + +It exposes the WSGI callable as a module-level variable named ``application``. + +For more information on this file, see +https://docs.djangoproject.com/en/1.11/howto/deployment/wsgi/ +""" + +import os + +from django.core.wsgi import get_wsgi_application + +os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings") + +application = get_wsgi_application() diff --git a/0621_test-master/django_app/post/admin.py b/0621_test-master/django_app/post/admin.py new file mode 100644 index 0000000000000000000000000000000000000000..da7127bdddc60824fafa16b71fe2403d88a4ecbb --- /dev/null +++ b/0621_test-master/django_app/post/admin.py @@ -0,0 +1,5 @@ +from django.contrib import admin + +from .models import Post + +admin.site.register(Post) diff --git a/0621_test-master/django_app/post/forms.py b/0621_test-master/django_app/post/forms.py new file mode 100644 index 0000000000000000000000000000000000000000..2629dfa4e70adbb48530d863b84185af11f72ede --- /dev/null +++ b/0621_test-master/django_app/post/forms.py @@ -0,0 +1,5 @@ +from django import forms + + +class CommentForm(forms.Form): + comment = forms.CharField(max_length=200) diff --git a/0621_test-master/django_app/post/migrations/0001_initial.py b/0621_test-master/django_app/post/migrations/0001_initial.py new file mode 100644 index 0000000000000000000000000000000000000000..5639033669bcb3998d428e0ab247063f48c73529 --- /dev/null +++ b/0621_test-master/django_app/post/migrations/0001_initial.py @@ -0,0 +1,25 @@ +# -*- coding: utf-8 -*- +# Generated by Django 1.11.2 on 2017-06-21 06:46 +from __future__ import unicode_literals + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [ + ] + + operations = [ + migrations.CreateModel( + name='Post', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('comment', models.CharField(max_length=200)), + ('created_date', models.DateTimeField(auto_now_add=True)), + ('modify_date', models.DateTimeField(auto_now=True)), + ], + ), + ] diff --git a/0621_test-master/django_app/post/tests.py b/0621_test-master/django_app/post/tests.py new file mode 100644 index 0000000000000000000000000000000000000000..7ce503c2dd97ba78597f6ff6e4393132753573f6 --- /dev/null +++ b/0621_test-master/django_app/post/tests.py @@ -0,0 +1,3 @@ +from django.test import TestCase + +# Create your tests here. diff --git a/0621_test-master/django_app/templates/post/post_list.html b/0621_test-master/django_app/templates/post/post_list.html new file mode 100644 index 0000000000000000000000000000000000000000..427de80592bd28603aa5bc97de30224b46175334 --- /dev/null +++ b/0621_test-master/django_app/templates/post/post_list.html @@ -0,0 +1,23 @@ + + + + + + + Document + + + +{% for post in posts %} + {{ post.comment }} + 靾橃爼 +
+ {% csrf_token %} + +
+
+{% endfor %} + + + \ No newline at end of file diff --git a/0621_test-master/django_app/templates/post/post_modify.html b/0621_test-master/django_app/templates/post/post_modify.html new file mode 100644 index 0000000000000000000000000000000000000000..d8fb42da001876c17d70b9ae35e1df22e0af3f00 --- /dev/null +++ b/0621_test-master/django_app/templates/post/post_modify.html @@ -0,0 +1,17 @@ + + + + + + + Document + + +
+ {% csrf_token %} + {{form}} + +
+ + \ No newline at end of file diff --git a/0621_test-master/requirements.txt b/0621_test-master/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..81bbf408d714d040bfdf856d735a8fb33bf9767a --- /dev/null +++ b/0621_test-master/requirements.txt @@ -0,0 +1,17 @@ +appnope==0.1.0 +decorator==4.0.11 +Django==1.11.2 +django-extensions==1.7.9 +ipython==6.1.0 +ipython-genutils==0.2.0 +jedi==0.10.2 +pexpect==4.2.1 +pickleshare==0.7.4 +prompt-toolkit==1.0.14 +ptyprocess==0.5.1 +Pygments==2.2.0 +pytz==2017.2 +simplegeneric==0.8.1 +six==1.10.0 +traitlets==4.3.2 +wcwidth==0.1.7 diff --git a/10-week-algorithm-excercise-master/.gitignore b/10-week-algorithm-excercise-master/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..4438f375cf9439f39a0acf3d7be98a2185b725fb --- /dev/null +++ b/10-week-algorithm-excercise-master/.gitignore @@ -0,0 +1,2 @@ +.idea/* +.idea diff --git a/10-week-algorithm-excercise-master/.pipreqs/requirements_pipreqs.txt b/10-week-algorithm-excercise-master/.pipreqs/requirements_pipreqs.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/10-week-algorithm-excercise-master/.pipreqs/requirements_pipreqs.txt @@ -0,0 +1 @@ + diff --git a/10-week-algorithm-excercise-master/OneQuestionPerDay/1/two_sum.go b/10-week-algorithm-excercise-master/OneQuestionPerDay/1/two_sum.go new file mode 100644 index 0000000000000000000000000000000000000000..f05ead4f3d52d7e8bd5e5cf4933745deed50c9bb --- /dev/null +++ b/10-week-algorithm-excercise-master/OneQuestionPerDay/1/two_sum.go @@ -0,0 +1,13 @@ +package main + +func twoSum(nums []int, target int) []int { + cache := make(map[int]int, 0) + for i, n := range nums { + m := target - n + if j, ok := cache[m]; ok { + return []int{j, i} + } + cache[n] = i + } + return nil +} diff --git a/10-week-algorithm-excercise-master/OneQuestionPerDay/1/two_sum.py b/10-week-algorithm-excercise-master/OneQuestionPerDay/1/two_sum.py new file mode 100644 index 0000000000000000000000000000000000000000..f68f592f5187424ea88f6f392a501884d89956f5 --- /dev/null +++ b/10-week-algorithm-excercise-master/OneQuestionPerDay/1/two_sum.py @@ -0,0 +1,11 @@ +from typing import List + +class Solution: + def twoSum(self, nums: List[int], target: int) -> List[int]: + cache = {} + for i, n in enumerate(nums): + m = target - n + if m in cache: + return [cache[m], i] + cache[n] = i + return [] \ No newline at end of file diff --git a/10-week-algorithm-excercise-master/OneQuestionPerDay/1021/remove_outermost_parentheses.go b/10-week-algorithm-excercise-master/OneQuestionPerDay/1021/remove_outermost_parentheses.go new file mode 100644 index 0000000000000000000000000000000000000000..3432b2197a1aac8e5f07d5c9d912d343ddd8950e --- /dev/null +++ b/10-week-algorithm-excercise-master/OneQuestionPerDay/1021/remove_outermost_parentheses.go @@ -0,0 +1,21 @@ +package main + +import "strings" + +func removeOuterParentheses(S string) string { + var strs []string + start := 0 + counter := 0 + for i, c := range S { + if c == '(' { + counter++ + } else { + counter-- + } + if counter == 0 { + strs = append(strs, S[start+1:i]) + start = i + 1 + } + } + return strings.Join(strs, "") +} diff --git a/10-week-algorithm-excercise-master/OneQuestionPerDay/1021/remove_outermost_parentheses_test.go b/10-week-algorithm-excercise-master/OneQuestionPerDay/1021/remove_outermost_parentheses_test.go new file mode 100644 index 0000000000000000000000000000000000000000..47067aeb0b45e437fd53cc5da5cdf1e2c28c1482 --- /dev/null +++ b/10-week-algorithm-excercise-master/OneQuestionPerDay/1021/remove_outermost_parentheses_test.go @@ -0,0 +1,23 @@ +package main + +import "testing" + +func Test(t *testing.T) { + tests := []struct { + S string + target string + }{ + {"", ""}, + {"()", ""}, + {"(())", "()"}, + {"()()", ""}, + {"(()())", "()()"}, + {"(()())((()))", "()()(())"}, + } + + for _, tt := range tests { + if ans := removeOuterParentheses(tt.S); ans != tt.target { + t.Fatalf("S: %s, target: %s, ans: %s\n", tt.S, tt.target, ans) + } + } +} diff --git a/10-week-algorithm-excercise-master/OneQuestionPerDay/104/maximum_depth_of_binary_tree2.go b/10-week-algorithm-excercise-master/OneQuestionPerDay/104/maximum_depth_of_binary_tree2.go new file mode 100644 index 0000000000000000000000000000000000000000..01f169ddb9ede0530cc393e79e65c64b8bb759da --- /dev/null +++ b/10-week-algorithm-excercise-master/OneQuestionPerDay/104/maximum_depth_of_binary_tree2.go @@ -0,0 +1,15 @@ +package main + +func maxDepth2(root *TreeNode) int { + if root == nil { + return 0 + } + return max(maxDepth2(root.Left), maxDepth2(root.Right)) + 1 +} + +func max(x, y int) int { + if x > y { + return x + } + return y +} diff --git a/10-week-algorithm-excercise-master/OneQuestionPerDay/104/maximum_depth_of_binary_tree2.py b/10-week-algorithm-excercise-master/OneQuestionPerDay/104/maximum_depth_of_binary_tree2.py new file mode 100644 index 0000000000000000000000000000000000000000..b25e1ba525aa00ea9e7fa2b40fbcba27157770d7 --- /dev/null +++ b/10-week-algorithm-excercise-master/OneQuestionPerDay/104/maximum_depth_of_binary_tree2.py @@ -0,0 +1,12 @@ +class TreeNode: + def __init__(self, x): + self.val = x + self.left = None + self.right = None + + +class Solution: + def maxDepth(self, root: TreeNode) -> int: + if root is None: + return 0 + return max(self.maxDepth(root.left), self.maxDepth(root.right)) + 1 diff --git a/10-week-algorithm-excercise-master/OneQuestionPerDay/15/3sum.py b/10-week-algorithm-excercise-master/OneQuestionPerDay/15/3sum.py new file mode 100644 index 0000000000000000000000000000000000000000..10ec57c5b86c68ccc5da47bb1f438b9e047076fe --- /dev/null +++ b/10-week-algorithm-excercise-master/OneQuestionPerDay/15/3sum.py @@ -0,0 +1,33 @@ +from typing import List + + +class Solution: + def threeSum(self, nums: List[int]) -> List[List[int]]: + nums.sort() + res = [] + for i in range(len(nums) - 2): + if nums[i] > 0: + break + if i > 0 and nums[i] == nums[i - 1]: + continue + + j, k = i + 1, len(nums) - 1 + while j < k: + s = nums[i] + nums[j] + nums[k] + if s == 0: + res.append([nums[i], nums[j], nums[k]]) + j += 1 + k -= 1 + while j < k and nums[j] == nums[j - 1]: + j += 1 + while j < k and nums[k] == nums[k + 1]: + k -= 1 + elif s > 0: + k -= 1 + while j < k and nums[k] == nums[k + 1]: + k -= 1 + else: + j += 1 + while j < k and nums[j] == nums[j - 1]: + j += 1 + return res diff --git a/10-week-algorithm-excercise-master/OneQuestionPerDay/15/3sum_test.go b/10-week-algorithm-excercise-master/OneQuestionPerDay/15/3sum_test.go new file mode 100644 index 0000000000000000000000000000000000000000..d9741c716d8fe5fe96274ddd1b1867568e1e0e9f --- /dev/null +++ b/10-week-algorithm-excercise-master/OneQuestionPerDay/15/3sum_test.go @@ -0,0 +1,23 @@ +package main + +import ( + "reflect" + "testing" +) + +func Test(t *testing.T) { + tests := []struct { + nums []int + target [][]int + }{ + {[]int{0,0,0}, [][]int{{0,0,0}}}, + {[]int{-1, 0, 1, 2, -1, -4}, [][]int{{-1, -1, 2}, {-1, 0, 1}}}, + } + + for _, tt := range tests { + if ans := threeSum(tt.nums); !reflect.DeepEqual(tt.target, ans) { + t.Fatalf("target: %v, ans: %v\n", tt.target, ans) + } + } + +} diff --git a/10-week-algorithm-excercise-master/OneQuestionPerDay/238/product_of_array_except_self.go b/10-week-algorithm-excercise-master/OneQuestionPerDay/238/product_of_array_except_self.go new file mode 100644 index 0000000000000000000000000000000000000000..fcc062160154e206f321da36fbf767c57c05f565 --- /dev/null +++ b/10-week-algorithm-excercise-master/OneQuestionPerDay/238/product_of_array_except_self.go @@ -0,0 +1,15 @@ +package main + +func productExceptSelf(nums []int) []int { + res := make([]int, len(nums)) + res[0] = 1 + for i := 1; i < len(nums); i++ { + res[i] = res[i-1] * nums[i-1] + } + r := 1 + for i := len(nums)-2;i >= 0;i-- { + r *= nums[i+1] + res[i] *= r + } + return res +} diff --git a/10-week-algorithm-excercise-master/OneQuestionPerDay/238/product_of_array_except_self.py b/10-week-algorithm-excercise-master/OneQuestionPerDay/238/product_of_array_except_self.py new file mode 100644 index 0000000000000000000000000000000000000000..dbd2f3c1707efa3816a12a98dbb198b8bb5bf895 --- /dev/null +++ b/10-week-algorithm-excercise-master/OneQuestionPerDay/238/product_of_array_except_self.py @@ -0,0 +1,15 @@ +from typing import List + + +class Solution: + def productExceptSelf(self, nums: List[int]) -> List[int]: + res = [0] * len(nums) + k = 1 + for i in range(len(nums)): + res[i] = k + k *= nums[i] + k = 1 + for i in range(len(nums) - 1, -1, -1): + res[i] *= k + k *= nums[i] + return res diff --git a/10-week-algorithm-excercise-master/OneQuestionPerDay/258/add_digits.go b/10-week-algorithm-excercise-master/OneQuestionPerDay/258/add_digits.go new file mode 100644 index 0000000000000000000000000000000000000000..3bd775b2aaeb24f1cdacddba8d4d2871551905a0 --- /dev/null +++ b/10-week-algorithm-excercise-master/OneQuestionPerDay/258/add_digits.go @@ -0,0 +1,13 @@ +package main + +func addDigits(num int) int { + for num > 9 { + sum := 0 + for num > 9 { + sum += num / 10 + num %= 10 + } + num += sum + } + return num +} diff --git a/10-week-algorithm-excercise-master/OneQuestionPerDay/258/add_digits2.go b/10-week-algorithm-excercise-master/OneQuestionPerDay/258/add_digits2.go new file mode 100644 index 0000000000000000000000000000000000000000..bab17e8d6f49f21dbc9d119e316b0d57224d487e --- /dev/null +++ b/10-week-algorithm-excercise-master/OneQuestionPerDay/258/add_digits2.go @@ -0,0 +1,9 @@ +package main + +func addDigits2(num int) int { + if num == 0 { + return 0 + } else { + return (num - 1) % 9 + 1 + } +} diff --git a/10-week-algorithm-excercise-master/OneQuestionPerDay/299/bulls_and_cows.go b/10-week-algorithm-excercise-master/OneQuestionPerDay/299/bulls_and_cows.go new file mode 100644 index 0000000000000000000000000000000000000000..dc2971a8e7e7579894a499cf84d91118b7660c86 --- /dev/null +++ b/10-week-algorithm-excercise-master/OneQuestionPerDay/299/bulls_and_cows.go @@ -0,0 +1,30 @@ +package main + +import "strconv" + +func getHint(secret string, guess string) string { + secretCount := make([]int, 10) + guessCount := make([]int, 10) + bulls := 0 + cows := 0 + + for i := 0; i < len(secret); i++ { + if secret[i] == guess[i] { + bulls++ + } else { + secretCount[secret[i]-'0']++ + guessCount[guess[i]-'0']++ + } + } + for i, v := range secretCount { + cows += min(v, guessCount[i]) + } + return strconv.Itoa(bulls) + "A" + strconv.Itoa(cows) + "B" +} + +func min(x, y int) int { + if x < y { + return x + } + return y +} diff --git a/10-week-algorithm-excercise-master/OneQuestionPerDay/299/bulls_and_cows.py b/10-week-algorithm-excercise-master/OneQuestionPerDay/299/bulls_and_cows.py new file mode 100644 index 0000000000000000000000000000000000000000..6dec7471bf9294ef19a05b62ebb1e6cd1a1d4f3a --- /dev/null +++ b/10-week-algorithm-excercise-master/OneQuestionPerDay/299/bulls_and_cows.py @@ -0,0 +1,15 @@ +class Solution: + def getHint(self, secret: str, guess: str) -> str: + secret_counter = [0] * 10 + guess_counter = [0] * 10 + bulls = cows = 0 + for i in range(len(secret)): + if secret[i] == guess[i]: + bulls += 1 + else: + secret_counter[ord(secret[i]) - ord('0')] += 1 + guess_counter[ord(guess[i]) - ord('0')] += 1 + for i in range(len(secret_counter)): + cows += min(secret_counter[i], guess_counter[i]) + + return f"{bulls}A{cows}B" diff --git a/10-week-algorithm-excercise-master/OneQuestionPerDay/299/bulls_and_cows_test.go b/10-week-algorithm-excercise-master/OneQuestionPerDay/299/bulls_and_cows_test.go new file mode 100644 index 0000000000000000000000000000000000000000..be86fc566769dc70b9985ec19436bd131634987d --- /dev/null +++ b/10-week-algorithm-excercise-master/OneQuestionPerDay/299/bulls_and_cows_test.go @@ -0,0 +1,21 @@ +package main + +import "testing" + +func Test(t *testing.T) { + tests := []struct { + secret string + guess string + target string + }{ + {"", "", "0A0B"}, + {"1807", "7810", "1A3B"}, + {"1123", "0111", "1A1B"}, + } + + for _, tt := range tests { + if ans := getHint(tt.secret, tt.guess); ans != tt.target { + t.Fatalf("target: %s, ans: %s\n", tt.target, ans) + } + } +} diff --git a/10-week-algorithm-excercise-master/OneQuestionPerDay/300/longest_increasing_subsequence.go b/10-week-algorithm-excercise-master/OneQuestionPerDay/300/longest_increasing_subsequence.go new file mode 100644 index 0000000000000000000000000000000000000000..014265f856f90da7786253c4441c9808260bc89e --- /dev/null +++ b/10-week-algorithm-excercise-master/OneQuestionPerDay/300/longest_increasing_subsequence.go @@ -0,0 +1,23 @@ +package main + +func max(x, y int) int { + if x > y { + return x + } + return y +} + +func lengthOfLIS(nums []int) int { + dp := make([]int, len(nums)) + res := 0 + for i := 0; i < len(nums); i++ { + dp[i] = 1 + for j := 0; j < i; j++ { + if nums[j] < nums[i] { + dp[i] = max(dp[i], dp[j]+1) + } + } + res = max(res, dp[i]) + } + return res +} diff --git a/10-week-algorithm-excercise-master/OneQuestionPerDay/300/longest_increasing_subsequence2.py b/10-week-algorithm-excercise-master/OneQuestionPerDay/300/longest_increasing_subsequence2.py new file mode 100644 index 0000000000000000000000000000000000000000..705629645d8b2b78844cd7ecbd9d051c1ddb0681 --- /dev/null +++ b/10-week-algorithm-excercise-master/OneQuestionPerDay/300/longest_increasing_subsequence2.py @@ -0,0 +1,19 @@ +from typing import List + + +class Solution: + def lengthOfLIS(self, nums: List[int]) -> int: + tail = [] + for i in range(len(nums)): + if i == 0 or nums[i] > tail[-1]: + tail.append(nums[i]) + else: + l, r = 0, len(tail) + while l < r: + m = (l + r) // 2 + if tail[m] < nums[i]: + l = m + 1 + else: + r = m + tail[l] = nums[i] + return len(tail) diff --git a/10-week-algorithm-excercise-master/OneQuestionPerDay/350/intersection_of_two_arrays_ii.go b/10-week-algorithm-excercise-master/OneQuestionPerDay/350/intersection_of_two_arrays_ii.go new file mode 100644 index 0000000000000000000000000000000000000000..e414ee03da69d4aafa351c5d1065ce995183656c --- /dev/null +++ b/10-week-algorithm-excercise-master/OneQuestionPerDay/350/intersection_of_two_arrays_ii.go @@ -0,0 +1,29 @@ +package main + +func intersect(nums1 []int, nums2 []int) []int { + counter1 := make(map[int]int, 0) + counter2 := make(map[int]int, 0) + + for _, n := range nums1 { + counter1[n]++ + } + for _, n := range nums2 { + counter2[n]++ + } + res := make([]int, 0) + for k, v1 := range counter1 { + if v2, ok := counter2[k]; ok { + for i := 0; i < min(v1, v2); i++ { + res = append(res, k) + } + } + } + return res +} + +func min(x, y int) int { + if x < y { + return x + } + return y +} diff --git a/10-week-algorithm-excercise-master/OneQuestionPerDay/387/first_unique_character_in_a_string.go b/10-week-algorithm-excercise-master/OneQuestionPerDay/387/first_unique_character_in_a_string.go new file mode 100644 index 0000000000000000000000000000000000000000..36d8e9e910332ea850d4f47ce56b6f09e6e321c0 --- /dev/null +++ b/10-week-algorithm-excercise-master/OneQuestionPerDay/387/first_unique_character_in_a_string.go @@ -0,0 +1,16 @@ +package main + +func firstUniqChar(s string) int { + arr := [26]int{} + + for i := 0;i < len(s);i++ { + arr[s[i]-'a'] = i + } + for i := 0 ; i < len(s);i++ { + if arr[s[i]-'a'] == i { + return i + } + arr[s[i]-'a'] = -1 + } + return -1 +} \ No newline at end of file diff --git a/10-week-algorithm-excercise-master/OneQuestionPerDay/412/fizz_buzz.py b/10-week-algorithm-excercise-master/OneQuestionPerDay/412/fizz_buzz.py new file mode 100644 index 0000000000000000000000000000000000000000..834d67fafe7294c14a8ca75922eab328c3752ec3 --- /dev/null +++ b/10-week-algorithm-excercise-master/OneQuestionPerDay/412/fizz_buzz.py @@ -0,0 +1,15 @@ +from typing import List + +class Solution: + def fizzBuzz(self, n: int) -> List[str]: + res = [] + for i in range(1, n+1): + if i % 15 == 0: + res.append("FizzBuzz") + elif i % 5 == 0: + res.append("Buzz") + elif i % 3 == 0: + res.append("Fizz") + else: + res.append(str(i)) + return res \ No newline at end of file diff --git a/10-week-algorithm-excercise-master/OneQuestionPerDay/412/fizz_buzz_test.go b/10-week-algorithm-excercise-master/OneQuestionPerDay/412/fizz_buzz_test.go new file mode 100644 index 0000000000000000000000000000000000000000..b6760fb13f2b65eb395b515421364386b71e8fcf --- /dev/null +++ b/10-week-algorithm-excercise-master/OneQuestionPerDay/412/fizz_buzz_test.go @@ -0,0 +1,40 @@ +package main + +import ( + "log" + "reflect" + "testing" +) + +func Test(t *testing.T) { + tests := []struct { + n int + target []string + }{ + {1, []string{"1"}}, + {3, []string{"1", "2", "Fizz"}}, + {15, []string{ + "1", + "2", + "Fizz", + "4", + "Buzz", + "Fizz", + "7", + "8", + "Fizz", + "Buzz", + "11", + "Fizz", + "13", + "14", + "FizzBuzz", + }}, + } + + for _, tt := range tests { + if ans := fizzBuzz(tt.n); !reflect.DeepEqual(ans, tt.target) { + log.Fatalf("n: %d, ans: %v\n", tt.n, ans) + } + } +} diff --git a/10-week-algorithm-excercise-master/OneQuestionPerDay/66/plus_one.py b/10-week-algorithm-excercise-master/OneQuestionPerDay/66/plus_one.py new file mode 100644 index 0000000000000000000000000000000000000000..937ffec7ef39e95fdf175325cc15e81f12982e0f --- /dev/null +++ b/10-week-algorithm-excercise-master/OneQuestionPerDay/66/plus_one.py @@ -0,0 +1,31 @@ +from typing import List + + +class Solution: + def plusOne(self, digits: List[int]) -> List[int]: + carry = True + for i in range(len(digits) - 1, -1, -1): + if digits[i] == 9: + digits[i] = 0 + else: + digits[i] += 1 + carry = False + break + if carry: + digits.insert(0, 1) + return digits + + def test(self): + + for digits, target in [ + ([1], [2]), + ([0], [1]), + ([9], [1, 0]), + ([2, 9, 9], [3, 0, 0]), + ]: + ans = self.plusOne(digits) + assert ans == target, f"target: {target}, ans {ans}" + + +if __name__ == "__main__": + Solution().test() diff --git a/10-week-algorithm-excercise-master/OneQuestionPerDay/66/plus_one_test.go b/10-week-algorithm-excercise-master/OneQuestionPerDay/66/plus_one_test.go new file mode 100644 index 0000000000000000000000000000000000000000..efd2f6a6486158e20167f974bb0b640ee25a207f --- /dev/null +++ b/10-week-algorithm-excercise-master/OneQuestionPerDay/66/plus_one_test.go @@ -0,0 +1,24 @@ +package main + +import ( + "reflect" + "testing" +) + +func Test(t *testing.T) { + tests := []struct { + digits []int + target []int + }{ + {[]int{0}, []int{1}}, + {[]int{1, 0}, []int{1, 1}}, + {[]int{1, 9}, []int{2, 0}}, + {[]int{9, 9}, []int{1, 0, 0}}, + } + + for _, tt := range tests { + if ans := plusOne(tt.digits); !reflect.DeepEqual(ans, tt.target) { + t.Fatalf("target : %v, ans: %v\n", tt.target, ans) + } + } +} diff --git a/10-week-algorithm-excercise-master/OneQuestionPerDay/718/maximum_length_of_repeated_subarray2.go b/10-week-algorithm-excercise-master/OneQuestionPerDay/718/maximum_length_of_repeated_subarray2.go new file mode 100644 index 0000000000000000000000000000000000000000..4faa04d264deb6ccade5314deabc9c5c71a27a77 --- /dev/null +++ b/10-week-algorithm-excercise-master/OneQuestionPerDay/718/maximum_length_of_repeated_subarray2.go @@ -0,0 +1,39 @@ +package main + +func findLength2(A []int, B []int) int { + m, n := len(A), len(B) + if m == 0 || n == 0 { + return 0 + } + res := 0 + + for i := 0; i < m; i++ { + l := min(m-i, n) + res = max(res, maxLen(A, i, B, 0, l)) + } + for i := 0; i < n; i++ { + l := min(n-i, m) + res = max(res, maxLen(A, 0, B, i, l)) + } + return res +} + +func min(x, y int) int { + if x < y { + return x + } + return y +} +func maxLen(a []int, i int, b []int, j int, m int) int { + res := 0 + k := 0 + for l := 0; l < m; l++ { + if a[i+l] == b[j+l] { + k++ + res = max(res, k) + } else { + k = 0 + } + } + return res +} diff --git a/10-week-algorithm-excercise-master/OneQuestionPerDay/718/maximum_length_of_repeated_subarray_test.go b/10-week-algorithm-excercise-master/OneQuestionPerDay/718/maximum_length_of_repeated_subarray_test.go new file mode 100644 index 0000000000000000000000000000000000000000..72b4d3815d3d00c331c9f9122bfa7c66361d9638 --- /dev/null +++ b/10-week-algorithm-excercise-master/OneQuestionPerDay/718/maximum_length_of_repeated_subarray_test.go @@ -0,0 +1,18 @@ +package main + +import "testing" + +func Test(t *testing.T) { + tests := []struct { + a []int + b []int + target int + }{ + {[]int{1,2,3}, []int{4,2,3}, 0}, + } + for _, tt := range tests { + if ans := findLength2(tt.a, tt.b); ans != tt.target { + t.Fatalf("target: %d, ans: %d\n", tt.target, ans) + } + } +} diff --git a/10-week-algorithm-excercise-master/OneQuestionPerDay/83/remove_duplicates_from_sorted_list.go b/10-week-algorithm-excercise-master/OneQuestionPerDay/83/remove_duplicates_from_sorted_list.go new file mode 100644 index 0000000000000000000000000000000000000000..ad15c8726941d34d1058e7013b9f08057d94ca58 --- /dev/null +++ b/10-week-algorithm-excercise-master/OneQuestionPerDay/83/remove_duplicates_from_sorted_list.go @@ -0,0 +1,23 @@ +package main + +type ListNode struct { + Val int + Next *ListNode +} + +func deleteDuplicates(head *ListNode) *ListNode { + if head == nil { + return head + } + elements := map[int]bool{head.Val: true} + prev, cur := head, head.Next + for cur != nil { + if elements[cur.Val] { + prev.Next, cur = cur.Next, cur.Next + } else { + elements[cur.Val] = true + prev, cur = cur, cur.Next + } + } + return head +} diff --git a/10-week-algorithm-excercise-master/OneQuestionPerDay/LCCI17/get_kth_magic_number2.go b/10-week-algorithm-excercise-master/OneQuestionPerDay/LCCI17/get_kth_magic_number2.go new file mode 100644 index 0000000000000000000000000000000000000000..56cebfd1d94714b68e3b0ea1970290f7f505c2f3 --- /dev/null +++ b/10-week-algorithm-excercise-master/OneQuestionPerDay/LCCI17/get_kth_magic_number2.go @@ -0,0 +1,47 @@ +package main + +import "container/heap" + +type IntHeap []int + +func (h IntHeap) Len() int { + return len(h) +} + +func (h IntHeap) Less(i, j int) bool { + return h[i] < h[j] +} + +func (h IntHeap) Swap(i, j int) { + h[i], h[j] = h[j], h[i] +} + +func (h *IntHeap) Push(x interface{}) { + *h = append(*h, x.(int)) +} +func (h *IntHeap) Pop() interface{} { + x := (*h)[len(*h)-1] + *h = (*h)[:len(*h)-1] + return x +} + +func getKthMagicNumber2(k int) int { + intHeap := &IntHeap{1} + heap.Init(intHeap) + visited := map[int]bool{1: true} + factors := [3]int{3, 5, 7} + n := 1 + i := 0 + for i < k { + i++ + n = (heap.Pop(intHeap)).(int) + for j := 0; j < len(factors); j++ { + m := n * factors[j] + if !visited[m] { + heap.Push(intHeap, m) + visited[m] = true + } + } + } + return n +} diff --git a/10-week-algorithm-excercise-master/OneQuestionPerDay/LCOF5/replace_space_test.go b/10-week-algorithm-excercise-master/OneQuestionPerDay/LCOF5/replace_space_test.go new file mode 100644 index 0000000000000000000000000000000000000000..eff07798ed5882ea46d7fc995e24a793d988c8b0 --- /dev/null +++ b/10-week-algorithm-excercise-master/OneQuestionPerDay/LCOF5/replace_space_test.go @@ -0,0 +1,23 @@ +package main + +import ( + "testing" +) + +func Test(t *testing.T) { + tests := []struct { + s string + target string + }{ + {"abc", "abc"}, + {"a bc", "a%20bc"}, + {" a bc", "%20a%20bc"}, + {" a bc ", "%20a%20bc%20"}, + } + + for _, tt := range tests { + if ans := replaceSpace(tt.s); ans != tt.target { + t.Fatalf("target: %s, ans: %s\n", tt.target, ans) + } + } +} diff --git a/10-week-algorithm-excercise-master/OneQuestionPerDay/LCOF59/max_sliding_window.py b/10-week-algorithm-excercise-master/OneQuestionPerDay/LCOF59/max_sliding_window.py new file mode 100644 index 0000000000000000000000000000000000000000..9dc637ea4884fa1770a443116f7fe3b8c92cce9c --- /dev/null +++ b/10-week-algorithm-excercise-master/OneQuestionPerDay/LCOF59/max_sliding_window.py @@ -0,0 +1,30 @@ +from typing import List +from collections import deque + + +class Solution: + def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]: + dq = deque() + res = [] + for i, n in enumerate(nums): + if len(dq) > 0 and dq[0] <= i - k: + dq.popleft() + while dq and nums[dq[-1]] < n: + dq.pop() + + dq.append(i) + if i >= k - 1: + res.append(nums[dq[0]]) + return res + + def test(self): + + for nums, k, target in [ + ([7, 2, 4], 2, [7, 4]) + ]: + ans = self.maxSlidingWindow(nums, k) + assert ans == target, f"target: {target}, ans: {ans}" + + +if __name__ == "__main__": + Solution().test() diff --git a/10-week-algorithm-excercise-master/README.md b/10-week-algorithm-excercise-master/README.md new file mode 100644 index 0000000000000000000000000000000000000000..a748f3fa392227c9d3097a4c34da4d18e99cbd3c --- /dev/null +++ b/10-week-algorithm-excercise-master/README.md @@ -0,0 +1,25 @@ +# 鏋佸澶у銆岀畻娉曡缁冭惀-绗16鏈熴嶄綔涓氭彁浜や粨搴 + + + + +## 浠撳簱鐩綍缁撴瀯璇存槑 + +1. `week01/` 浠h〃绗竴鍛ㄤ綔涓氭彁浜ょ洰褰曪紝浠ユ绫绘帹銆 +2. 璇峰湪瀵瑰簲鍛ㄧ殑鐩綍涓嬫柊寤烘垨淇敼鑷繁鐨勪唬鐮佷綔涓氥 +2. 姣忓懆鍧囨湁涓涓 `REDAME.md` 鏂囨。锛屼綘鍙互灏嗚嚜宸卞綋鍛ㄧ殑瀛︿範蹇冨緱浠ュ強鍋氶杩囩▼涓殑鎬濊冭褰曞湪璇ユ枃妗d腑銆 + +## 浣滀笟鎻愪氦瑙勫垯 + +1. 鍏堝皢鏈粨搴 Fork 鍒拌嚜宸 GitHub 璐﹀彿涓嬨 +2. 灏 Fork 鍚庣殑浠撳簱 Clone 鍒版湰鍦帮紝鐒跺悗鍦ㄦ湰鍦颁粨搴撲腑瀵瑰簲鍛ㄧ殑鐩綍涓嬫柊寤烘垨淇敼鑷繁鐨勪唬鐮佷綔涓氾紝褰撳懆鐨勫涔犳荤粨鍐欏湪瀵瑰簲鍛ㄧ殑README.md鏂囦欢閲屻 +3. 鍦ㄦ湰鍦颁粨搴撳畬鎴愪綔涓氬悗锛宲ush 鍒拌嚜宸辩殑 GitHub 杩滅▼浠撳簱銆 +4. 鏈鍚庡皢杩滅▼浠撳簱涓綋鍛ㄧ殑浣滀笟閾炬帴锛屾寜鏍煎紡璐村埌鐝骇浠撳簱瀵瑰簲瀛︿範鍛ㄧ殑issue涓嬮潰銆 +5. 鎻愪氦issue璇峰姟蹇呮寜鐓ц瀹氭牸寮忚繘琛屾彁浜わ紝鍚﹀垯浣滀笟缁熻宸ュ叿灏嗘姄鍙栦笉鍒颁綘鐨勪綔涓氭彁浜よ褰曘 + +璇︾粏鐨勪綔涓氭彁浜ゆ祦绋嬪彲浠ユ煡闃咃細https://shimo.im/docs/m5rtM8K8rNsjw5jk/ + + +## 娉ㄦ剰浜嬮」 + + 濡傛灉瀵 Git 鍜 GitHub 涓嶅お浜嗚В锛岃鍙傝 [Git 瀹樻柟鏂囨。](https://git-scm.com/book/zh/v2) 鎴栬呮瀬瀹㈡椂闂寸殑[銆婄帺杞 Git 涓夊墤瀹€媇(https://time.geekbang.org/course/intro/145)瑙嗛璇剧▼銆 diff --git a/10-week-algorithm-excercise-master/Week_01/1/two_sum_test.go b/10-week-algorithm-excercise-master/Week_01/1/two_sum_test.go new file mode 100644 index 0000000000000000000000000000000000000000..b2d0100ad532c81f6464f1ccfad4ed347985784a --- /dev/null +++ b/10-week-algorithm-excercise-master/Week_01/1/two_sum_test.go @@ -0,0 +1,23 @@ +package main + +import ( + "reflect" + "testing" +) + +func Test(t *testing.T) { + tests := []struct { + nums []int + sum int + target []int + }{ + {[]int{1, 3, 5}, 4, []int{0, 1}}, + {[]int{1, 3, 5, 2}, 3, []int{0, 3}}, + } + + for _, tt := range tests { + if ans := twoSum(tt.nums, tt.sum); !reflect.DeepEqual(ans, tt.target) { + t.Fatalf("target: %v, ans %v\n", tt.target, ans) + } + } +} diff --git a/10-week-algorithm-excercise-master/Week_01/141/linked_list_cycle.py b/10-week-algorithm-excercise-master/Week_01/141/linked_list_cycle.py new file mode 100644 index 0000000000000000000000000000000000000000..4157f1caa9cc2ce032feec7d829e4a8f5e9b5d9c --- /dev/null +++ b/10-week-algorithm-excercise-master/Week_01/141/linked_list_cycle.py @@ -0,0 +1,40 @@ +class ListNode: + def __init__(self, x): + self.val = x + self.next = None + + +class Solution: + def hasCycle(self, head: ListNode) -> bool: + seen = {} + while head is not None: + if head in seen: + return True + seen[head] = True + head = head.next + return False + + def test(self): + n1 = ListNode(1) + n2 = ListNode(2) + n3 = ListNode(3) + n4 = ListNode(4) + n2.next = n1 + n3.next = n2 + n4.next = n3 + + assert not self.hasCycle(n1) + assert not self.hasCycle(n2) + assert not self.hasCycle(n3) + assert not self.hasCycle(n4) + n1.next = n3 + assert self.hasCycle(n1) + assert self.hasCycle(n2) + assert self.hasCycle(n3) + assert self.hasCycle(n4) + + print("all done") + + +if __name__ == "__main__": + Solution().test() diff --git a/10-week-algorithm-excercise-master/Week_01/141/linked_list_cycle2.py b/10-week-algorithm-excercise-master/Week_01/141/linked_list_cycle2.py new file mode 100644 index 0000000000000000000000000000000000000000..8fffc399ad4d73d387a412648e64a4d0ada67e9d --- /dev/null +++ b/10-week-algorithm-excercise-master/Week_01/141/linked_list_cycle2.py @@ -0,0 +1,42 @@ +class ListNode: + def __init__(self, x): + self.val = x + self.next = None + + +class Solution: + def hasCycle(self, head: ListNode) -> bool: + if head is None or head.next is None: + return False + slow, fast = head, head.next + while fast is not None and fast.next is not None: + if slow == fast: + return True + slow = slow.next + fast = fast.next.next + return False + + def test(self): + n1 = ListNode(1) + n2 = ListNode(2) + n3 = ListNode(3) + n4 = ListNode(4) + n2.next = n1 + n3.next = n2 + n4.next = n3 + + assert not self.hasCycle(n1) + assert not self.hasCycle(n2) + assert not self.hasCycle(n3) + assert not self.hasCycle(n4) + n1.next = n3 + assert self.hasCycle(n1) + assert self.hasCycle(n2) + assert self.hasCycle(n3) + assert self.hasCycle(n4) + + print("all done") + + +if __name__ == "__main__": + Solution().test() diff --git a/10-week-algorithm-excercise-master/Week_01/15/3sum_2.go b/10-week-algorithm-excercise-master/Week_01/15/3sum_2.go new file mode 100644 index 0000000000000000000000000000000000000000..2d005de5ff8de47573ab0ccba5687b5c43f6008b --- /dev/null +++ b/10-week-algorithm-excercise-master/Week_01/15/3sum_2.go @@ -0,0 +1,45 @@ +package main + +import "sort" + +func threeSum2(nums []int) [][]int { + sort.Ints(nums) + var ret [][]int + + for i := 0; i < len(nums)-2; i++ { + if nums[i] > 0 { + break + } + if i > 0 && nums[i] == nums[i-1] { + continue + } + l, r := i+1, len(nums)-1 + for l < r { + b, c := nums[l], nums[r] + s := nums[i] + b + c + if s == 0 { + ret = append(ret, []int{nums[i], b, c}) + l++ + r-- + for r > 0 && nums[r] == c { + r-- + } + for l < len(nums) && nums[l] == b { + l++ + } + } else if s > 0 { + r-- + for r > 0 && nums[r] == c { + r-- + } + } else { + l++ + for l < len(nums) && nums[l] == b { + l++ + } + } + } + } + + return ret +} diff --git a/10-week-algorithm-excercise-master/Week_01/189/rotate_array2.py b/10-week-algorithm-excercise-master/Week_01/189/rotate_array2.py new file mode 100644 index 0000000000000000000000000000000000000000..2ea3d8ebe71f553eb2f30283f50baf5fdfcfd57e --- /dev/null +++ b/10-week-algorithm-excercise-master/Week_01/189/rotate_array2.py @@ -0,0 +1,21 @@ +from typing import List + + +class Solution: + def rotate(self, nums: List[int], k: int) -> None: + """ + Do not return anything, modify nums in-place instead. + """ + + def reverse(arr: List[int], start: int, end: int): + while start < end: + arr[start], arr[end] = arr[end], arr[start] + start += 1 + end -= 1 + + n = len(nums) + k = k % n + reverse(nums, 0, n - 1) + reverse(nums, 0, k - 1) + reverse(nums, k, n - 1) + diff --git a/10-week-algorithm-excercise-master/Week_01/20/valid_parentheses.py b/10-week-algorithm-excercise-master/Week_01/20/valid_parentheses.py new file mode 100644 index 0000000000000000000000000000000000000000..308a694cb7f3c197b50607fca9225b042ddd7d14 --- /dev/null +++ b/10-week-algorithm-excercise-master/Week_01/20/valid_parentheses.py @@ -0,0 +1,29 @@ +class Solution: + def isValid(self, s: str) -> bool: + pairs = { + "}": "{", + "]": "[", + ")": "(", + } + stack = ["?"] + + for c in s: + if c not in pairs: + stack.append(c) + elif stack.pop() != pairs[c]: + return False + return len(stack) == 1 + + def test(self): + for s, target in [ + ("{", False), + ("{[", False), + ("{}", True), + ("{()}", True), + ("{()))", False), + ]: + assert target is self.isValid(s), f"failed. s: {s}" + + +if __name__ == "__main__": + Solution().test() diff --git a/10-week-algorithm-excercise-master/Week_01/206/reverse_linked_list2.go b/10-week-algorithm-excercise-master/Week_01/206/reverse_linked_list2.go new file mode 100644 index 0000000000000000000000000000000000000000..d3caddafaa84401906898a63c967e66ac7fa1d96 --- /dev/null +++ b/10-week-algorithm-excercise-master/Week_01/206/reverse_linked_list2.go @@ -0,0 +1,17 @@ +package main + +// Definition for singly-linked list. +type ListNode struct { + Val int + Next *ListNode +} + +func reverseList(head *ListNode) *ListNode { + if head == nil || head.Next == nil{ + return head + } + current := reverseList(head.Next) + head.Next.Next = head + head.Next = nil + return current +} diff --git a/10-week-algorithm-excercise-master/Week_01/21/merge_two_sorted_lists2.go b/10-week-algorithm-excercise-master/Week_01/21/merge_two_sorted_lists2.go new file mode 100644 index 0000000000000000000000000000000000000000..5d52cba1937b769e6a7b907e0a1b0ecb09202f32 --- /dev/null +++ b/10-week-algorithm-excercise-master/Week_01/21/merge_two_sorted_lists2.go @@ -0,0 +1,15 @@ +package main + +func mergeTwoLists2(l1 *ListNode, l2 *ListNode) *ListNode { + if l1 == nil { + return l2 + } else if l2 == nil { + return l1 + } else if l1.Val < l2.Val { + l1.Next = mergeTwoLists2(l1.Next, l2) + return l1 + } else { + l2.Next = mergeTwoLists2(l2.Next, l1) + return l2 + } +} diff --git a/10-week-algorithm-excercise-master/Week_01/24/swap_nodes_in_pairs.py b/10-week-algorithm-excercise-master/Week_01/24/swap_nodes_in_pairs.py new file mode 100644 index 0000000000000000000000000000000000000000..b067f84f439b6163f403c060b73b8b297b5fcac6 --- /dev/null +++ b/10-week-algorithm-excercise-master/Week_01/24/swap_nodes_in_pairs.py @@ -0,0 +1,14 @@ +class ListNode: + def __init__(self, x): + self.val = x + self.next = None + + +class Solution: + def swapPairs(self, head: ListNode) -> ListNode: + if head is None or head.next is None: + return head + next_ = head.next + head.next = self.swapPairs(next_.next) + next_.next = head + return next_ diff --git a/10-week-algorithm-excercise-master/Week_01/24/swap_nodes_in_pairs2.go b/10-week-algorithm-excercise-master/Week_01/24/swap_nodes_in_pairs2.go new file mode 100644 index 0000000000000000000000000000000000000000..74d53d4a617f8a25d0b88a54ffb535ad76c16938 --- /dev/null +++ b/10-week-algorithm-excercise-master/Week_01/24/swap_nodes_in_pairs2.go @@ -0,0 +1,13 @@ +package main + +func swapPairs(head *ListNode) *ListNode { + dummy := &ListNode{0, head} + prev := dummy + for head != nil && head.Next != nil { + prev.Next = head.Next + prev = head + head.Next, head.Next.Next = head.Next.Next, head + head = head.Next + } + return dummy.Next +} diff --git a/10-week-algorithm-excercise-master/Week_01/25/reverse_nodes_in_k_group_test.go b/10-week-algorithm-excercise-master/Week_01/25/reverse_nodes_in_k_group_test.go new file mode 100644 index 0000000000000000000000000000000000000000..4eb2dde725e143f4e5a7c5aa941cae04f1e6e146 --- /dev/null +++ b/10-week-algorithm-excercise-master/Week_01/25/reverse_nodes_in_k_group_test.go @@ -0,0 +1,21 @@ +package main + +import ( + "fmt" + "testing" +) + +func Test(t *testing.T) { + n1 := &ListNode{1, nil} + n2 := &ListNode{2, n1} + n3 := &ListNode{3, n2} + n4 := &ListNode{4, n3} + n5 := &ListNode{5, n4} + + k := 6 + head := reverseKGroup(n5, k) + for head != nil { + fmt.Printf("%d-->", head.Val) + head = head.Next + } +} \ No newline at end of file diff --git a/10-week-algorithm-excercise-master/Week_01/42/trapping_rain_water.py b/10-week-algorithm-excercise-master/Week_01/42/trapping_rain_water.py new file mode 100644 index 0000000000000000000000000000000000000000..04bc683427fa7e545ba896b95762f31c23e1e2ad --- /dev/null +++ b/10-week-algorithm-excercise-master/Week_01/42/trapping_rain_water.py @@ -0,0 +1,34 @@ +from typing import List + + +class Solution: + def trap(self, height: List[int]) -> int: + + stack = [] + res = 0 + + for i, h in enumerate(height): + while stack and height[stack[-1]] < h: + top = stack.pop() + if not stack: + break + left = stack[-1] + res += (i - left - 1) * (min(h, height[left]) - height[top]) + stack.append(i) + return res + + def test(self): + for height, target in [ + ([], 0), + ([1, 1], 0), + ([1, 0, 0], 0), + ([1, 0, 1], 1), + ([0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1], 6), + ]: + ans = self.trap(height) + assert ans == target, f"target: {target}, ans {ans}" + print("all done") + + +if __name__ == "__main__": + Solution().test() diff --git a/10-week-algorithm-excercise-master/Week_01/641/design_circular_deque2.py b/10-week-algorithm-excercise-master/Week_01/641/design_circular_deque2.py new file mode 100644 index 0000000000000000000000000000000000000000..644e46638becfd685b22a23862e0fd8e75807a27 --- /dev/null +++ b/10-week-algorithm-excercise-master/Week_01/641/design_circular_deque2.py @@ -0,0 +1,82 @@ +class MyCircularDeque: + + def __init__(self, k: int): + """ + Initialize your data structure here. Set the size of the deque to be k. + """ + self.size = k + self.len = 0 + self.head = 0 + self.tail = 0 + self.queue = [0] * k + + def insertFront(self, value: int) -> bool: + """ + Adds an item at the front of Deque. Return true if the operation is successful. + """ + if self.isFull(): + return False + self.head = (self.head + 1) % self.size + self.queue[self.head] = value + self.len += 1 + return True + + def insertLast(self, value: int) -> bool: + """ + Adds an item at the rear of Deque. Return true if the operation is successful. + """ + if self.isFull(): + return False + self.queue[self.tail] = value + self.tail = (self.tail + self.size - 1) % self.size + self.len += 1 + return True + + def deleteFront(self) -> bool: + """ + Deletes an item from the front of Deque. Return true if the operation is successful. + """ + if self.isEmpty(): + return False + self.len -= 1 + self.head = (self.head - 1 + self.size) % self.size + return True + + def deleteLast(self) -> bool: + """ + Deletes an item from the rear of Deque. Return true if the operation is successful. + """ + + if self.isEmpty(): + return False + self.len -= 1 + self.tail = (self.tail + 1) % self.size + return True + + def getFront(self) -> int: + """ + Get the front item from the deque. + """ + if self.isEmpty(): + return -1 + return self.queue[self.head] + + def getRear(self) -> int: + """ + Get the last item from the deque. + """ + if self.isEmpty(): + return -1 + return self.queue[(self.tail + 1) % self.size] + + def isEmpty(self) -> bool: + """ + Checks whether the circular deque is empty or not. + """ + return self.len == 0 + + def isFull(self) -> bool: + """ + Checks whether the circular deque is full or not. + """ + return self.len == self.size diff --git a/10-week-algorithm-excercise-master/Week_01/70/climbing_stairs.py b/10-week-algorithm-excercise-master/Week_01/70/climbing_stairs.py new file mode 100644 index 0000000000000000000000000000000000000000..2d649c297b77f97669ac1215118eeb635bcf3d3d --- /dev/null +++ b/10-week-algorithm-excercise-master/Week_01/70/climbing_stairs.py @@ -0,0 +1,23 @@ +class Solution: + def climbStairs(self, n: int) -> int: + if n < 3: + return n + f1, f2 = 1, 2 + for i in range(3, n+1): + f2, f1, = f1 + f2, f2 + return f2 + + def test(self): + for n, target in [ + (1, 1), + (2, 2), + (3, 3), + (4, 5), + (5, 8), + ]: + ans = self.climbStairs(n) + assert ans == target, f"n {n}, ans {ans}, target {target}" + + +if __name__ == "__main__": + Solution().test() diff --git a/10-week-algorithm-excercise-master/Week_01/70/climbing_stairs_test.go b/10-week-algorithm-excercise-master/Week_01/70/climbing_stairs_test.go new file mode 100644 index 0000000000000000000000000000000000000000..092f52dd3387a1d668964531b4e9a0b8a23a780f --- /dev/null +++ b/10-week-algorithm-excercise-master/Week_01/70/climbing_stairs_test.go @@ -0,0 +1,23 @@ +package main + +import ( + "testing" +) + +func Test(t *testing.T) { + tests := []struct { + n int + target int + }{ + {1, 1}, + {2, 2}, + {3, 3}, + {4, 5}, + } + + for _, tt := range tests { + if ans := climbStairs(tt.n); ans != tt.target { + t.Fatalf("n: %d, ans %d, target %d\n", tt.n, ans, tt.target) + } + } +} diff --git a/10-week-algorithm-excercise-master/Week_01/84/largest_rectangle_in_histogram3.go b/10-week-algorithm-excercise-master/Week_01/84/largest_rectangle_in_histogram3.go new file mode 100644 index 0000000000000000000000000000000000000000..8facfa20e09c4c4deaa99637efcfd0cb905b29b0 --- /dev/null +++ b/10-week-algorithm-excercise-master/Week_01/84/largest_rectangle_in_histogram3.go @@ -0,0 +1,18 @@ +package main + +func largestRectangleArea(heights []int) int { + res := 0 + var stack []int + heights = append([]int{0}, heights...) + heights = append(heights, 0) + + for i, h := range heights { + for len(stack) > 1 && h < heights[stack[len(stack)-1]] { + idx := stack[len(stack)-1] + res = max(res, heights[idx]*(i-stack[len(stack)-2]-1)) + stack = stack[:len(stack)-1] + } + stack = append(stack, i) + } + return res +} diff --git a/10-week-algorithm-excercise-master/Week_01/84/largest_rectangle_in_histogram_test.go b/10-week-algorithm-excercise-master/Week_01/84/largest_rectangle_in_histogram_test.go new file mode 100644 index 0000000000000000000000000000000000000000..f6017d187dab3de902ad330161822abd9645ca81 --- /dev/null +++ b/10-week-algorithm-excercise-master/Week_01/84/largest_rectangle_in_histogram_test.go @@ -0,0 +1,21 @@ +package main + +import ( + "testing" +) + +func Test(t *testing.T) { + tests := []struct { + heights []int + target int + }{ + {[]int{}, 0}, + {[]int{2, 1, 5, 6, 2, 3}, 10}, + } + + for _, tt := range tests { + if ans := largestRectangleArea(tt.heights); ans != tt.target { + t.Fatalf("target: %d, ans锛 %d\n", tt.target, ans) + } + } +} diff --git a/10-week-algorithm-excercise-master/Week_01/88/merge_sorted_array.go b/10-week-algorithm-excercise-master/Week_01/88/merge_sorted_array.go new file mode 100644 index 0000000000000000000000000000000000000000..b32b7768cf9965c33637974a12107a458ba4fd18 --- /dev/null +++ b/10-week-algorithm-excercise-master/Week_01/88/merge_sorted_array.go @@ -0,0 +1,13 @@ +package main + +func merge0(nums1 []int, m int, nums2 []int, n int) { + i := 0 + for j := 0; j < n; j++ { + for nums1[i] <= nums2[j] && i < m+j { + i++ + } + copy(nums1[i+1:m+j+1], nums1[i:m+j]) + nums1[i] = nums2[j] + i++ + } +} diff --git a/10-week-algorithm-excercise-master/Week_01/88/merge_sorted_array_test.go b/10-week-algorithm-excercise-master/Week_01/88/merge_sorted_array_test.go new file mode 100644 index 0000000000000000000000000000000000000000..eca4fc8fe6348f19c0fe12e00b6a76443a029a9c --- /dev/null +++ b/10-week-algorithm-excercise-master/Week_01/88/merge_sorted_array_test.go @@ -0,0 +1,30 @@ +package main + +import ( + "reflect" + "sort" + "testing" +) + +func Test(t *testing.T) { + t.Helper() + tests := []struct { + nums1 []int + m int + nums2 []int + n int + }{ + {[]int{0, 0}, 0, []int{1, 5}, 2}, + {[]int{0, 0, 0}, 1, []int{1, 5}, 2}, + {[]int{3,7, 30, 0, 0}, 3, []int{1, 5}, 2}, + {[]int{1, 4, 9, 0, 0}, 3, []int{1, 5}, 2}, + } + for _, tt := range tests { + target := append(tt.nums2, tt.nums1[:tt.m]...) + sort.Ints(target) + if merge(tt.nums1, tt.m, tt.nums2, tt.n); !reflect.DeepEqual(tt.nums1, target) { + t.Fatalf("target: %v, ans: %v\n", target, tt.nums1) + } + + } +} diff --git a/10-week-algorithm-excercise-master/Week_02/242/valid_anagram.py b/10-week-algorithm-excercise-master/Week_02/242/valid_anagram.py new file mode 100644 index 0000000000000000000000000000000000000000..4889cde1aea712ed5d691e4a2628647cbf225425 --- /dev/null +++ b/10-week-algorithm-excercise-master/Week_02/242/valid_anagram.py @@ -0,0 +1,16 @@ +class Solution: + def isAnagram(self, s: str, t: str) -> bool: + if len(s) != len(t): + return False + + counter = [0] * 26 + + for c in s: + counter[ord(c) - ord('a')] += 1 + for c in t: + counter[ord(c) - ord('a')] -= 1 + + for i in counter: + if i != 0: + return False + return True diff --git a/10-week-algorithm-excercise-master/Week_02/242/valid_anagram_test.go b/10-week-algorithm-excercise-master/Week_02/242/valid_anagram_test.go new file mode 100644 index 0000000000000000000000000000000000000000..b877ecdbfcfda1ec6576b95faedee95628f51713 --- /dev/null +++ b/10-week-algorithm-excercise-master/Week_02/242/valid_anagram_test.go @@ -0,0 +1,22 @@ +package main + +import "testing" + +func Test(t *testing.T) { + tests := []struct { + s string + t string + target bool + }{ + {"", "", true}, + {"a", "", false}, + {"", "a", false}, + {"abc", "aca", false}, + } + + for _, tt := range tests { + if ans := isAnagram(tt.s, tt.t); ans != tt.target { + t.Fatalf("failed. %s %s\n", tt.s, tt.t) + } + } +} diff --git a/10-week-algorithm-excercise-master/Week_02/347/top_k_frequent_elements.py b/10-week-algorithm-excercise-master/Week_02/347/top_k_frequent_elements.py new file mode 100644 index 0000000000000000000000000000000000000000..d8ec7b8cb515c947d81addfb72417f9ff4b8c4c2 --- /dev/null +++ b/10-week-algorithm-excercise-master/Week_02/347/top_k_frequent_elements.py @@ -0,0 +1,33 @@ +from typing import List +from collections import defaultdict +import heapq + + +class Solution: + def topKFrequent(self, nums: List[int], k: int) -> List[int]: + counter = defaultdict(int) + for n in nums: + counter[n] += 1 + heap = [] + i = 0 + for key, v in counter.items(): + if i < k: + heapq.heappush(heap, [v, key]) + i += 1 + elif i >= k and v > heap[0][0]: + heapq.heapreplace(heap, [v, key]) + return [h[1] for h in heap] + + def test(self): + for nums, k, target in [ + ([1], 1, [1]), + ([1, 1, 1, 2, 3, 3, 4], 2, [1, 3]), + ]: + ans = self.topKFrequent(nums, k) + assert sorted(ans) == target, f"target: {target}, ans: {ans}" + + print("well done") + + +if __name__ == "__main__": + Solution().test() diff --git a/10-week-algorithm-excercise-master/Week_02/429/n_ary_tree_level_order_traversal2.py b/10-week-algorithm-excercise-master/Week_02/429/n_ary_tree_level_order_traversal2.py new file mode 100644 index 0000000000000000000000000000000000000000..ab61cbb0be2bd23e7f20a7673364141c5087ffd9 --- /dev/null +++ b/10-week-algorithm-excercise-master/Week_02/429/n_ary_tree_level_order_traversal2.py @@ -0,0 +1,27 @@ +from typing import List + + +class Node: + def __init__(self, val=None, children=None): + self.val = val + self.children = children + + +class Solution: + def levelOrder(self, root: 'Node') -> List[List[int]]: + res = [] + level = 0 + stack = [root] + while stack: + num = len(stack) + for i in range(num): + if stack[i] is not None: + if len(res) == level: + res.append([stack[i].val]) + else: + res[level].append(stack[i].val) + for c in stack[i].children: + stack.append(c) + stack = stack[num:] + level += 1 + return res diff --git a/10-week-algorithm-excercise-master/Week_02/94/binary_tree_inorder_traversal3.py b/10-week-algorithm-excercise-master/Week_02/94/binary_tree_inorder_traversal3.py new file mode 100644 index 0000000000000000000000000000000000000000..e7200fdafaceb70a6b4ace19a1320ee5514960ff --- /dev/null +++ b/10-week-algorithm-excercise-master/Week_02/94/binary_tree_inorder_traversal3.py @@ -0,0 +1,42 @@ +from typing import List + + +class TreeNode: + def __init__(self, x): + self.val = x + self.left = None + self.right = None + + +class Solution: + def inorderTraversal(self, root: TreeNode) -> List[int]: + res = [] + while root is not None: + if root.left is None: + res.append(root.val) + root = root.right + else: + pre = root.left + while pre.right is not None: + pre = pre.right + + pre.right = root + root = root.left + pre.right.left = None + return res + + def test(self): + n1 = TreeNode(1) + n2 = TreeNode(2) + n3 = TreeNode(3) + + n1.right = n2 + n2.left = n3 + + ans = self.inorderTraversal(n1) + assert ans == [1, 3, 2], f"ans: {ans}" + print("well done") + + +if __name__ == "__main__": + Solution().test() diff --git a/10-week-algorithm-excercise-master/Week_03/104/maximum_depth_of_binary_tree.go b/10-week-algorithm-excercise-master/Week_03/104/maximum_depth_of_binary_tree.go new file mode 100644 index 0000000000000000000000000000000000000000..d0c7ea4c483b5e30469348b4141b9f09d0026a42 --- /dev/null +++ b/10-week-algorithm-excercise-master/Week_03/104/maximum_depth_of_binary_tree.go @@ -0,0 +1,25 @@ +package main + +type TreeNode struct { + Val int + Left *TreeNode + Right *TreeNode +} + +func max(x, y int) int { + if x > y { + return x + } + return y +} + +func dfs(node *TreeNode) int { + if node == nil { + return 0 + } + return max(dfs(node.Left), dfs(node.Right)) + 1 +} + +func maxDepth(root *TreeNode) int { + return dfs(root) +} diff --git a/10-week-algorithm-excercise-master/Week_03/105/construct_binary_tree_from_preorder_and_inorder_traversal.go b/10-week-algorithm-excercise-master/Week_03/105/construct_binary_tree_from_preorder_and_inorder_traversal.go new file mode 100644 index 0000000000000000000000000000000000000000..0f33fff1458fb7cc7c362e81fdd53e2f5931137d --- /dev/null +++ b/10-week-algorithm-excercise-master/Week_03/105/construct_binary_tree_from_preorder_and_inorder_traversal.go @@ -0,0 +1,24 @@ +package main + +type TreeNode struct { + Val int + Left *TreeNode + Right *TreeNode +} + +func buildTree(preorder []int, inorder []int) *TreeNode { + if len(preorder) == 0 { + return nil + } + root := &TreeNode{Val: preorder[0]} + i := 0 + + for ; i < len(inorder); i++ { + if inorder[i] == preorder[0] { + break + } + } + root.Left = buildTree(preorder[1:i+1], inorder[:i]) + root.Right = buildTree(preorder[i+1:], inorder[i+1:]) + return root +} diff --git a/10-week-algorithm-excercise-master/Week_03/169/majority_element.py b/10-week-algorithm-excercise-master/Week_03/169/majority_element.py new file mode 100644 index 0000000000000000000000000000000000000000..206885bed1526dd45199818b87c2a6976f1385f3 --- /dev/null +++ b/10-week-algorithm-excercise-master/Week_03/169/majority_element.py @@ -0,0 +1,15 @@ +from typing import List + + +class Solution: + def majorityElement(self, nums: List[int]) -> int: + counter = {} + half_len = len(nums) // 2 + for n in nums: + if n in nums: + counter[n] += 1 + else: + counter[n] = 1 + if counter[n] > half_len: + return n + return -1 diff --git a/10-week-algorithm-excercise-master/Week_03/README.md b/10-week-algorithm-excercise-master/Week_03/README.md new file mode 100644 index 0000000000000000000000000000000000000000..9380eb12e84b6b0d35568947167bd0f183244e8b --- /dev/null +++ b/10-week-algorithm-excercise-master/Week_03/README.md @@ -0,0 +1,116 @@ +瀛︿範绗旇 + +|#|Title|Solutions| +|---|---|------| +|70|[climbing-stairs](https://leetcode-cn.com/problems/climbing-stairs) | 閫掑綊([Go](70/climbing_stairs.go),[Py](70/climbing_stairs.py))| +|22|[generate-parentheses](https://leetcode-cn.com/problems/generate-parentheses) | 閫掑綊([Go](22/generate_parentheses.go),[Py](22/generate_parentheses.py))| +|226|[invert-binary-tree](https://leetcode-cn.com/problems/invert-binary-tree) | 閫掑綊([Go](226/invert_binary_tree.go),[Py](226/invert_binary_tree.go)),闃熷垪([Go](226/invert_binary_tree2.go))| +|98|[validate-binary-search-tree](https://leetcode-cn.com/problems/validate-binary-search-tree) | 閫掑綊([Go](98/validate_binary_search_tree.go),[Py](98/validate_binary_search_tree.py)),涓簭閬嶅巻([Go](98/validate_binary_search_tree2.go),[Py](98/validate_binary_search_tree2.py))| +|104|[maximum-depth-of-binary-tree](https://leetcode-cn.com/problems/maximum-depth-of-binary-tree) | 閫掑綊([Go](104/maximum_depth_of_binary_tree.go))| +|111|[minimum-depth-of-binary-tree](https://leetcode-cn.com/problems/minimum-depth-of-binary-tree) | 閫掑綊([Go](111/minimum_depth_of_binary_tree.go),[Py](111/minimum_depth_of_binary_tree.py)),灞傚簭閬嶅巻([Go](111/minimum_depth_of_binary_tree2.go),[Py](111/minimum_depth_of_binary_tree2.py))| +|236|[lowest-common-ancestor-of-a-binary-tree](https://leetcode-cn.com/problems/lowest-common-ancestor-of-a-binary-tree) | 閫掑綊([Go](236/lowest_common_ancestor_of_a-binary_tree.go),[Py](236/lowest_common_ancestor_of_a-binary_tree.py)),閬嶅巻璁板綍鐖惰妭鐐([Go](236/lowest_common_ancestor_of_a-binary_tree2.go),[Py](236/lowest_common_ancestor_of_a-binary_tree2.py))| +|297|[serialize-and-deserialize-binary-tree](https://leetcode-cn.com/problems/serialize-and-deserialize-binary-tree/) | 灞傚簭閬嶅巻([Go](297/serialize_and_deserialize_binary_tree.go),[Py](297/serialize_and_deserialize_binary_tree.py)),閫掑綊鍓嶅簭閬嶅巻([Go](297/serialize_and_deserialize_binary_tree2.go),[Py](297/serialize_and_deserialize_binary_tree2.py))| +|105|[construct-binary-tree-from-preorder-and-inorder-traversal](https://leetcode-cn.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal) | 閫掑綊([Go](105/construct_binary_tree_from_preorder_and_inorder_traversal.go),[Py](105/construct_binary_tree_from_preorder_and_inorder_traversal.py))| +|77|[combinations](https://leetcode-cn.com/problems/combinations) | 閫掑綊([Go](77/combinations.go),[Py](77/combinations.go))| +|46|[permutations](https://leetcode-cn.com/problems/permutations) | 閫掑綊([Go](46/permutations.go),[Py](46/permutations.py))| +|47|[permutations-ii](https://leetcode-cn.com/problems/permutations-ii) | 閫掑綊([Go](47/permutations.go),[Py](47/permutations.py))| +|50|[powx_n](https://leetcode-cn.com/problems/powx-n) | 閫掑綊([Go](50/powx_n.go),[Py](50/powx_n.py))| +|78|[subsets](https://leetcode-cn.com/problems/subsets) | 閫掑綊([Go](78/subsets.go),[Py](78/subsets.py))| +|169|[majority-element](https://leetcode-cn.com/problems/majority-element) | 鍝堝笇琛([Go](169/majority_element.go),[Py](169/majority_element.py)),璁℃暟鎶曠エ([Go](169/majority_element2.go),[Py](169/majority_element2.py))| +|17|[letter-combinations-of-a-phone-number](https://leetcode-cn.com/problems/letter-combinations-of-a-phone-number) | 閫掑綊([Go](17/letter_combinations_of_a_phone_number.go),[Py](17/letter_combinations_of_a_phone_number.go))| +|51|[n-queens](https://leetcode-cn.com/problems/n-queens) | 鍥炴函([Go](51/n_queens.go),[Py](51/n_queens.py))| + + +## 棰樿В + +### 70. climbing-stairs + +闄や簡閫掓帹澶栦篃鍙互鐢ㄩ掑綊锛屼笉杩囨秹鍙婂埌閲嶅璁$畻锛岄渶瑕佺敤鍝堝笇琛ㄥ仛缂撳瓨 + +### 22. generate-parentheses + +閫掑綊 + +### 226. invert-binary-tree + +1. 閫掑綊 +2. 闃熷垪 + +### 98. validate-binary-search-tree + +1. 閫掑綊 +2. 涓簭閬嶅巻 + +### 111. minimum-depth-of-binary-tree + +1. 閫掑綊 +2. 浣跨敤闃熷垪閫愬眰閬嶅巻 + +### 236. lowest-common-ancestor-of-a-binary-tree + +1. 閫掑綊 + - 濡傛灉root鏄痯鎴杚,鍒欐渶杩戝叕鍏辩鍏堝氨鏄痳oot + - 鍚庣画閬嶅巻 + - 濡傛灉left鍜宺ight閮芥湁鎵惧埌锛岄偅灏辨槸root + - 濡傛灉left娌℃壘鍒帮紝閭h繑鍥瀝ight(right鍙兘鏃秐il)锛況ight娌℃壘鍒颁害鐒 +2. 寤2涓搱甯岃〃锛屼竴涓褰曠埗鑺傜偣锛屽彟涓涓褰曟槸鍚﹁闂繃 + + +### 297. serialize-and-deserialize-binary-tree/ + +1. 浣跨敤闃熷垪灞傚簭閬嶅巻 +2. 閫掑綊鍓嶅簭閬嶅巻 + +### 297. construct-binary-tree-from-preorder-and-inorder-traversal + +1. 閫掑綊 + - 鍓嶅簭閬嶅巻鐨勭涓涓厓绱犱负root + - 鍦ㄤ腑搴忛亶鍘嗕腑鎵惧埌root鐨刬ndex锛屼粠鑰屽緱鍑哄乏鍙冲瓙鏍戠殑闀垮害 + - 閫掑綊宸﹀彸瀛愭爲 + +### 77. combinations + +1. 閫掑綊 + - 鎻愬墠寤虹珛涓涓暱搴︿负k鐨勭┖鏁扮粍 + - 閫掑綊姣忔濉竴涓暟 + - 绗琸涓嵆涓虹粨鏋 + +### 46. permutations + +1. 閫掑綊+鍥炴函 + - 鎻愬墠寤虹珛涓涓暱搴︿负k鐨勭┖鏁扮粍,骞跺缓绔嬩竴涓悓鏍烽暱搴︿负k鐨勭┖鏁扮粍鐢ㄤ簬鏍囪瘑鏄惁宸茶浣跨敤 + - 閫掑綊姣忔濉竴涓暟 + - 绗琸涓嵆涓虹粨鏋 + +### 47. permutations-ii + +1. 閫掑綊+鍥炴函 + - 鎻愬墠寤虹珛涓涓暱搴︿负k鐨勭┖鏁扮粍,骞跺缓绔嬩竴涓瓧鍏歌褰曞綋鍓嶆瘡涓厓绱犲墿浣欑殑涓暟 + - 閫掑綊姣忔濉竴涓暟 + - 绗琸涓嵆涓虹粨鏋 + + +### 50. powx-n + +1. 閫掑綊 + - n涓0鏃惰繑鍥1 + - n<0鏃讹細n=-n,x = 1/x + +### 78. subsets + +1. 閫掑綊 + +### 169. majority-element + +1. 鍝堝笇琛細閬嶅巻璁板綍姣忎釜鍏冪礌鍑虹幇鐨勬鏁帮紝澶т簬len(nums)/2鍗充负浼楁暟 +2. 璁℃暟鎶曠エ锛氱敤涓涓暣鏁板彉閲廲ount鍋氳鏁帮紝閬囧埌浼楁暟+1锛岄潪浼楁暟-1锛屾渶鍚巆ount蹇呭畾澶т簬0锛屽搴旂殑candidate鍗充负浼楁暟 + + +### 17. letter-combinations-of-a-phone-number + +1. 閫掑綊 + + +### 51. n-queens + +1. 鍥炴函 \ No newline at end of file