<jupyter_start><jupyter_text>From the qasm 3.0 code, make a decomposition in which only the gates of the Clifford+T group remain, and then identify if the number of gates can be reduced, e.g.What can the following quantum circuits be reduced to?The gates i need to consider changing are RX, RY, RZ,  CCX,  and reduce them if exist the case.<jupyter_code>import numpy as np
from qiskit.circuit import QuantumCircuit
from qiskit.circuit.library import TGate, HGate, TdgGate,SGate
from qiskit.converters import circuit_to_dag, dag_to_circuit
from qiskit.transpiler.passes.synthesis.solovay_kitaev import SolovayKitaevDecomposition
from qiskit.quantum_info import Operator
from itertools  import tee,islice<jupyter_output><empty_output><jupyter_text>For cost it is always optimal to use clifford+t gate of the unitary gates. But it is a problem finding accurate clifford+ gate combination for unitary circuit like rz,rx,ry.So there is various works have been attemted in different way to approximate the combination of clifford+t gate based with better precision and better  memory capability.where there is many papers i had to read to tackle this problem with better algorithm and ring and group of mathematics to optimize the issue  but among all those papers i found some algorithm very promising.but i have used  the most oldest one solovay-kitaev  to solve this.at first i have understood the algoeithm then used a file and added it to my qiskit environment changing some  code in files which is given in the github repo.the problem i found with it is it's huge memory inefficient but better  precision.the maximum time i have spent to understand the algorithm optimal ancilla-free clifford+t approximation of z rotation.i read it haskell file and read exact synthesis algorithm .this  2 algorithms main advantafge is  that  they reduce the space for u.z>=1-e**2.  then solve diophantine equation to solve it.it is memory efficient.as i have used solovay kitaev approach here , i will try ti implement exact synthesis algorithm in my later works as i was  fascinated by those approach.but this all are developement of solovay kitaev which  think the prime approach,that's why i have used this approach here.i have read this papers till i finally stuck  with solovay kitaev approach.1.'Optimal ancilla-free Clifford+T approximation of z-rotations'-<NAME> and <NAME>- 'https://arxiv.org/pdf/1403.2975.pdf' -ring modulas approach2.'<NAME> and <NAME>. Exact and approximate synthesis of quantum circuits, version 0.3.0.1. Software implementation, http://www.mathstat.dal.ca/~selinger/newsynth/3.'a. Fast and efficient exact synthesis of single qubit unitaries generated by Clifford and T gate'- <NAME>, <NAME>, and <NAME>. F-' rXiv:1206.5236v4.        this paper haws taken sde gde approach which is exponenetial approach.        4.'Asymptotically optimal approximation of single qubit unitaries by Clifford and T circuits using a constant number of ancillary qubits. '- arXiv:1212.0822v2. for the demonstration part pseducode:    1.taking a function of rz with input parameter,circuit,qubit number where it will insert    2.use solovay kitaev decomposition  from my qiskit environment which is added and then transform it into qasm file with qc.qasm()    3.opening that file and reading that file i tried to replace some string to make it viable for using as a file,compatible woth making circuit and reduction    4.in inverese  qasm  parse function   i tried to read file where every gate and it's parameter  is in one line to make a circuit .it then takes to circuit.    5.i have opted to work with string because it will help me to reduce some string with appropriate string (gates with appropriate reduction gates)  the via 4.    take it to the circuit.<jupyter_code>def rz(x,circuit,qubit):
    
  
    circuit.rz(x,qubit )
    dag = circuit_to_dag(circuit)

    basis_gates = [TGate(), TdgGate(), HGate()]
    skd = SolovayKitaevDecomposition(recursion_degree=2, basis_gates=basis_gates)

    discretized = dag_to_circuit(skd.run(dag))

    pp=discretized.qasm()

    with open('ss1.qasm', 'w') as f:
        print(pp,file=f)
    def parse_qasm(qasm):
    
        lns = qasm.split(',')
        n = (lns[0])
 

    #gates = [l.split(" ") for l in lns[4:] if l]
        gates = [l.split("") for l in lns[3:] if l]
        return {'n': n, 'gates': gates, 'n_gates': len(gates)}

    def parse_qasm_file(fname,fname1):
    
        a = ['OPENQASM 2.0;','include "qelib1.inc";','qreg q[1];']
    
        with open(fname) as fin, open(fname1 , "w+") as fout:
            lines=fin.readlines()
            p=[]
            l=[]
            for i in range(4):
                p.append(lines[i::3])
        
            ll=[''.join(str(twos))+'\n' for twos in zip(*p)]

            for line in ll:
                for word in a:
                  line = line.replace(word, "1")
                line=line.replace(';',"")
                line=line.replace('q[',"")
                line=line.replace(']',"")
                line=line.replace('(',"")
                line=line.replace(')',"")
            
                line=line.replace('n',"")
                line=line.replace(',',"")
                line=line.replace("'","")
               
                line=line.replace('  \ ','  '  )
                line=line.replace('tdg','T')

                
            
                fout.write(line)


            fin.close()
            fout.close()
             #gates = [l.split(" ") for l in lns[4:] if l]
   
    
        return parse_qasm(open(fname1).read())
    gg=parse_qasm_file('ss1.qasm','ss567112390.qasm')


    print(gg)

#l=[' '.join(twos) for twos in zip(gates[::2],gates[1::2])]

    

    
def inverse_parse_file(fname1,qubit):
        

        with open(fname1+str(qubit)+'.qasm') as fin ,open(fname1+str(qubit+1)+'.qasm ','w+') as fout :

            l=fin.read().split(str(qubit)+' ')
            for line in l:

                fout.write(line+str(qubit)+' '+'\n')


            
        
            fin.close()
            fout.close()
            
        
        qc=QuantumCircuit(2)
        with open(fname1+str(qubit+1)+'.qasm') as fin:
            l=fin.readlines()
            count=0
       
            for line in l:
            
                if 'cx' in line :
                    ll=[]
                    for i in range(len(line)):
                        if line[i]!= 'c' and line[i]!='x' and line[i]!= ' ' and line[i]!= '\n':
                           ll.append(line[i] )
                    qc.cx(int(ll[0]),int(ll[1]))
                    count=count+1
                if 'T' in line :
                    ll=[]
                    for i in range(len(line)):
                        if line[i]!= 'h' and line[i]!= 't' and  line[i]!= 'T'  and line[i]!= ' ' and line[i]!= '\n':
                            ll.append(line[i] )
                    qc.tdg(int(ll[0]))
                    count=count+1
                if 't' in line :
                    ll=[]
                    for i in range(len(line)):
                        if line[i]!= 'h' and line[i]!= 't' and  line[i]!= 'T'  and line[i]!= ' ' and line[i]!= '\n':
                           ll.append(line[i] )
                    qc.t(int(ll[0]))
                    count=count+1
                if 'h' in line :
                    ll=[]
                    for i in range(len(line)):
                        if line[i]!= 'h' and line[i]!= 't' and  line[i]!= 'T'  and line[i]!= ' ' and line[i]!= '\n':
                           ll.append(line[i] )
                    qc.h(int(ll[0]))
                    count=count+1

                if 'ccx'  in line:
                    ll=[]
                    for i in range(len(line)):
                        if line[i] !='c'   and line[i] !='x' and  line[i] != ' ' and line[i] != '\n':
                            ll.append(line[i])
                    
                    ccx(int(ll[0]),int(ll[1]),int(ll[2]),qc)   
        print( qc.draw())

gh=inverse_parse_file('ss56711239',0)<jupyter_output>┌───┐┌───┐┌───┐┌───┐┌─────┐┌───┐┌─────┐┌───┐┌─────┐┌───┐┌───┐┌───┐┌───┐»
q_0: ┤ T ├┤ H ├┤ T ├┤ H ├┤ Tdg ├┤ H ├┤ Tdg ├┤ H ├┤ Tdg ├┤ T ├┤ H ├┤ T ├┤ H ├»
     ├───┤└───┘└───┘└───┘└─────┘└───┘└─────┘└───┘└─────┘└───┘└───┘└───┘└───┘»
q_1: ┤ T ├──────────────────────────────────────────────────────────────────»
     └───┘                                                                  »
«     ┌───┐┌───┐┌─────┐┌───┐┌─────┐┌───┐┌─────┐┌───┐┌───┐┌───┐┌───┐┌─────┐┌───┐»
«q_0: ┤ T ├┤ H ├┤ Tdg ├┤ H ├┤ Tdg ├┤ H ├┤ Tdg ├┤ T ├┤ H ├┤ T ├┤ H ├┤ Tdg ├┤ H ├»
«     └───┘└───┘└─────┘└───┘└─────┘└───┘└─────┘└───┘└───┘└───┘└───┘└─────┘└───┘»
«q_1: ─────────────────────────────────────────────────────────────────────────»
«                                                                              »
«     ┌─────┐┌───┐┌───┐┌───┐┌───┐┌───┐┌───┐┌───┐┌───┐┌───┐┌───┐┌─────┐┌───┐»
«q_0: ┤ Tdg ├┤ T ├┤ H ├┤ T ├┤ H ├┤ T ├┤ H ├┤ T ├┤ H ├┤ T ├┤ H ├┤ Tdg ├┤ H ├»
«     └─────┘└───┘└───┘└───┘└───┘└───┘└───┘└───┘└──[...]<jupyter_text>for this part of the task i have taken ncv decomposition approach  which take any ccu circuit to  cv and cv+ gate.where cv and cv+ gate transform to  h+ctc+h+tpattern.i have used the concrete decomposed circuit here  but in future work i will try to develope this file so that it will take ncv  and put it in string and replace that struing with h+ctc+h+t pattern and then from string we will design circuit.the paper which helped me most here-1. https://www.scirp.org/pdf/JAMP_2019111414372907.pdf-'  The Mapping and Optimization Method of Quantum Circuits for Clifford + T Gate .'<jupyter_code>def ccx(ii,j,k,qc):
    
    qc.h(k)
    qc.cx(j,k)
    qc.tdg(k)
    qc.cx(ii,k)
    qc.t(k)
    qc.cx(ii,j)
    qc.tdg(k)
    qc.cx(ii,k)
    qc.t(ii)
    qc.t(k)
    qc.cx(ii,j)
    qc.h(k)
    qc.t(ii)
    qc.tdg(j)
    qc.cx(ii,j)
    pppp=qc.qasm()
    with open('ss1.qasm', 'w') as f:
        print(pppp,file=f)




    def parse_qasm(qasm):
        lns = qasm.split(',')
        n = (lns[0])
    
        gates = [l.split("") for l in lns[3:] if l]
    

        return {'n': n, 'gates': gates, 'n_gates': len(gates)}

    def parse_qasm_file(fname,fname1):
    
        a = ['OPENQASM 2.0;','include "qelib1.inc";','qreg q[1];']
    
        with open(fname) as fin, open(fname1 , "w+") as fout:
            lines=fin.readlines()
            p=[]
            l=[]
            for i in range(4):
                p.append(lines[i::4])
        
            ll=[''.join(str(twos))+'\n' for twos in zip(*p)]


            for line in ll:
                for word in a:
                  line = line.replace(word, "1")
                line=line.replace(';',"")
                line=line.replace('q[',"")
                line=line.replace(']',"")
                line=line.replace('(',"")
                line=line.replace(')',"")
            
                line=line.replace('n',"")
                line=line.replace(',',"")
                line=line.replace("'","")
            #line=line.replace(" 0\ "," ")
            #line=line.replace(" 0"," ")
                line=line.replace('\ ','  ' )
                line=line.replace('tdg','T')

            #line=line.replace('tdg tdg','sdg')
            
            
            

        
            
            
                fout.write(line)


            fin.close()
            fout.close()
        return parse_qasm(open(fname1).read())
    





    

            
    gg=parse_qasm_file('ss1.qasm','ss56711230.qasm')


    print(gg)

#l=[' '.join(twos) for twos in zip(gates[::2],gates[1::2])]

    

    gh=inverse_parse_file('ss5671123')



    print(gh)<jupyter_output><empty_output><jupyter_text>here i have drawn the given circuit.  i have written the circuit and took it to qasm file. and read from it.<jupyter_code>import numpy as np
from qiskit.circuit import QuantumCircuit
from qiskit.circuit.library import TGate, HGate, TdgGate,SGate
from qiskit.converters import circuit_to_dag, dag_to_circuit
from qiskit.transpiler.passes.synthesis.solovay_kitaev import SolovayKitaevDecomposition
from qiskit.quantum_info import Operator
from itertools  import tee,islice

circuit = QuantumCircuit(1)
circuit.rz(np.pi/5,0 )
dag = circuit_to_dag(circuit)

print('Original circuit:')
print(circuit.draw())

basis_gates = [TGate(), TdgGate(), HGate()]
skd = SolovayKitaevDecomposition(recursion_degree=2, basis_gates=basis_gates)

discretized = dag_to_circuit(skd.run(dag))





qc = QuantumCircuit(3)
qc.h(0)
qc.y(1)
qc.h(2)
qc.cx(0,1)
qc.ccx(0,1,2)
qc.z(1)
qc.rz(np.pi/5,2)

pppp=qc.qasm()


#print('Discretized circuit:')
##print(discretized.draw())

#print('Error:', np.linalg.norm(Operator(circuit).data - Operator(discretized).data))


with open('ss1.qasm', 'w') as f:
    print(pppp,file=f)




def parse_qasm(qasm):
    """Parse qasm from a string.
    """
    lns = qasm.split(',')
    n = (lns[0])
 

    #gates = [l.split(" ") for l in lns[4:] if l]
    
    gates = [l.split("") for l in lns[3:] if l]
    

    return {'n': n, 'gates': gates, 'n_gates': len(gates)}

def parse_qasm_file(fname,fname1):
    
    a = ['OPENQASM 2.0;','include "qelib1.inc";','qreg q[1];']
    
    with open(fname) as fin, open(fname1 , "w+") as fout:
        lines=fin.readlines()
        p=[]
        l=[]
        for i in range(4):
            p.append(lines[i::4])
        
        ll=[''.join(str(twos))+'\n' for twos in zip(*p)]


        for line in ll:
            for word in a:
               line = line.replace(word, "1")
            line=line.replace(';',"")
            line=line.replace('q[',"")
            line=line.replace(']',"")
            line=line.replace('(',"")
            line=line.replace(')',"")
            
            line=line.replace('n',"")
            line=line.replace(',',"")
            line=line.replace("'","")
            #line=line.replace(" 0\ "," ")
            #line=line.replace(" 0"," ")
            line=line.replace('\ ','  ' )
            #line=line.replace('tdg','T')

            #line=line.replace('tdg tdg','sdg')
            
            
            

        
            
            
            fout.write(line)


        fin.close()
        fout.close()
             #gates = [l.split(" ") for l in lns[4:] if l]
   
    """Parse a qasm file.
    """
    return parse_qasm(open(fname1).read())
    





    

            
gg=parse_qasm_file('ss1.qasm','ss567112380.qasm')


print(gg)

#l=[' '.join(twos) for twos in zip(gates[::2],gates[1::2])]
def inverse_parse_file(fname1):
        for i in range(10):

            with open(fname1+str(i)+'.qasm') as fin ,open(fname1+str(i+1)+'.qasm ','w+') as fout :

                l=fin.read().split(str(i)+' ')
                for line in l:

                    fout.write(line+str(i)+' '+'\n')


            
        
                fin.close()
                fout.close()
            
        
        qc=QuantumCircuit(3)
        with open(fname1+str(10)+'.qasm') as fin:
            l=fin.readlines()
            count=0
       
            for line in l:
            
                if 'cx' in line :
                    ll=[]
                    for i in range(len(line)):
                        if line[i]!= 'c' and line[i]!='x' and line[i]!= ' ' and line[i]!= '\n':
                           ll.append(line[i] )
                    qc.cx(int(ll[0]),int(ll[1]))
                    count=count+1
                if 'T' in line :
                    ll=[]
                    for i in range(len(line)):
                        if line[i]!= 'T'  and line[i]!= ' ' and line[i]!= '\n':
                            ll.append(line[i] )
                    qc.tdg(int(ll[0]))
                    count=count+1
                if 't' in line :
                    ll=[]
                    for i in range(len(line)):
                        if line[i]!= 't'  and line[i]!= ' ' and line[i]!= '\n':
                           ll.append(line[i] )
                    qc.t(int(ll[0]))
                    count=count+1
                if 'h' in line :
                    ll=[]
                    for i in range(len(line)):
                        if line[i]!= 'h'  and line[i]!= ' ' and line[i]!= '\n':
                           ll.append(line[i] )
                    qc.h(int(ll[0]))
                    count=count+1

                if 'ccx'  in line:
                    ll=[]
                    for i in range(len(line)):
                        if line[i] !='c'   and line[i] !='x' and  line[i] != ' ' and line[i] != '\n':
                            ll.append(line[i])
                    
                    ccx(int(ll[0]),int(ll[1]),int(ll[2]),qc)   
        return  qc.draw()
    

                    
    

gh=inverse_parse_file('ss56711238')



print(gh)<jupyter_output>Original circuit:
     ┌─────────┐
q_0: ┤ Rz(π/5) ├
     └─────────┘
{'n': '1  1  qreg 3  h 0\\\ny 1  h 2  cx 01  ccx 012\\\n', 'gates': [], 'n_gates': 0}
{'n': '1  1  qreg 3  h 0\\\nh 2  cx 01  cx 01  h 2\\\ncx 12  T 2  cx 02  t 2\\\ncx 01  T 2  cx 02  t 0\\\nt 2  cx 01  h 2  t 0\\\n', 'gates': [], 'n_gates': 0}
     ┌───┐                                            ┌───┐     ┌───┐
q_0: ┤ H ├──■────■────────────────■────■───────────■──┤ T ├──■──┤ T ├
     └───┘┌─┴─┐┌─┴─┐              │  ┌─┴─┐         │  └───┘┌─┴─┐└───┘
q_1: ─────┤ X ├┤ X ├──■───────────┼──┤ X ├─────────┼───────┤ X ├─────
     ┌───┐├───┤└───┘┌─┴─┐┌─────┐┌─┴─┐├───┤┌─────┐┌─┴─┐┌───┐├───┤     
q_2: ┤ H ├┤ H ├─────┤ X ├┤ Tdg ├┤ X ├┤ T ├┤ Tdg ├┤ X ├┤ T ├┤ H ├─────
     └───┘└───┘     └───┘└─────┘└───┘└───┘└─────┘└───┘└───┘└───┘     
     ┌───┐                                            ┌───┐      ┌───┐      
q_0: ┤ H ├──■────■────────────────■────■───────────■──┤ T ├──■───┤ T ├───■──
     └───┘┌─┴─┐┌─┴─┐              │  ┌─┴─[...]<jupyter_text>reinforcement learning  greedy policy technique approachTo do reduction i have developed my algoriithm  to make it  reinforcement learning technique  to do the reduction part.it is designed to  check any combination to get the lowest cost(here it is circuit number )  to take the best combination (combination is number of combinatiopn where each number represents a function where the function takes the information which string will replace to which according to reduction pattern ).my string approach have made it easier for me to read files  and detect pattern there and replace it with it's valid pattern got from reduction algorithomes.the approach check every qubit for that pattern to replace it.  here it is desingned tthe cost functipn(circuit number)1.function is cretaed with opening a file of string and writing it into file.when it will get' number' it's gona apply number+\n to cretae a file which is gonna contains lines where every line will contain one gate and it's parameters2.during inverse partse amd reading the file during reading every gate it's gonna increase count  to finally give us circuit numbers. for this cost function calling.<jupyter_code>def cost(fname):
    for i in range(10):
        with open(fname+str(i)+'.qasm') as fin ,open(fname+str(i+1)+'.qasm ','w+') as fout :
            l=fin.read().split(str(i)+' ')
            for line in l:
               fout.write(line+str(i)+' '+'\n')


            
        
            fin.close()
            fout.close()
        
        with open(fname+str(10)+'.qasm') as fin:
            l=fin.readlines()
            count=0
       
            for line in l:
            
                if 'cx' in line :
                    ll=[]
                    for i in range(len(line)):
                        if line[i]!= 'c' and line[i]!='x' and line[i]!= ' ' and line[i]!= '\n':
                           ll.append(line[i] )
                    qc.cx(int(ll[0]),int(ll[1]))
                    count=count+1
                if 'T' in line :
                    ll=[]
                    for i in range(len(line)):
                        if line[i]!= 'T'  and line[i]!= ' ' and line[i]!= '\n':
                            ll.append(line[i] )
                    qc.tdg(int(ll[0]))
                    count=count+1
                if 't' in line :
                    ll=[]
                    for i in range(len(line)):
                        if line[i]!= 't'  and line[i]!= ' ' and line[i]!= '\n':
                           ll.append(line[i] )
                    qc.t(int(ll[0]))
                    count=count+1
                if 'h' in line :
                    ll=[]
                    for i in range(len(line)):
                        if line[i]!= 'h'  and line[i]!= ' ' and line[i]!= '\n':
                           ll.append(line[i] )
                    qc.h(int(ll[0]))
                    count=count+1
        return count<jupyter_output><empty_output><jupyter_text>this is checkijng pattern function .1.during every pattern function it will check string of specific pattern for all the qubits  and calculate cost after ward.function's output will be cost.which applies the conditon of the circuit after checking this pattern.2.i have taken dictionaries  where every number contains function                                                             reinforcement learning1. i have used permutation to permuate the numbers in dictionaries. i have checked cost for all permuatations items where every permuation item consist dictnumbers or prermutation of functions where fumction contains pattern2.then i have taken minimum cost that which permutation gives minimum  cost. then i have taken the first value of that permutation which will be the dict number or pattern.this dictnumbver or pattern function is best  because it gives minimum cost where the cost is calculated from all the next pattern it can check from here .it is best for this moment.so it's taken and it's removed from dictionary. this demonstrates one of the rl algorithm greedy policy.Reinforcement Learning: An Introduction - Stanford UniversitySutton & Barto Book: Reinforcement Learning: An Introduction3.then went to 1. with remaining dictionary number and repeated the scheme for all thye numbers until permuation term is 0.4.inverse parse function is applied to demonstrate the circuit according to best permutation pattern checking list.<jupyter_code>def checking_pattern(x,fname):
    from itertools import  permutations
    def cxhhcx(fname1,fname2,num_qubits):
        p=[]
        for i in range(num_qubits):
            p.append(i)
        perm=permutations(p)

        with open(fname1) as fin, open(fname2,'w+') as fout:
            lines=fin.readlines()
            for i in range(x): 
               for line in lines:
                   for item in list(perm):
                        j  in list(item)
                        line=line.replace('cx'+' '+str(j[0])+str(j[1])+' '+'h'+" "+str(j[0])+' '+'h'+' '+str(j[1])+' '+ 'cx'+' '+str(j[0])+str(j[1])+' '+'h'+" "+str(j[0])+' '+'h'+' '+str(j[1])+' '+'cx'+' '+str(j[0])+str(j[1])+' '+'h'+" "+str(j[0])+' '+'h'+' '+ str(j[1]),'cx'+' '+str(j[0])+str(j[1])+' '+'cx'+' '+str(j[1])+str(j[0])+' '+'cx'+' '+str(j[0])+str(j[1]))
                        fout.write()
            fin.close()
            fout.close()
        return cost(fname2)
    
    def cxcx2to3(fname1,fname2,num_qubits):
        p=[]
        for i in range(num_qubits):
            p.append(i)
        perm=permutations(p)

        with open(fname1) as fin, open(fname2,'w+') as fout:
            lines=fin.readlines()
            for i in range(x): 
               for line in lines:
                    for item in list(perm):
                        j  = list(item)
                        line=line.replace('cx'+' '+str(j[1])+str(j[2])+' '+'cx'+' '+str(j[0])+str(j[1]),'cx'+' '+str(j[0])+str(j[1])+' '+'cx'+' '+str(j[1])+str(j[2])+' '+'cx'+' '+str(j[0])+str(j[2]))
                        fout.write()
            fin.close()
            fout.close()
        return cost(fname2)
    def cxcxcx(fname1,fname2,num_qubits):
        p=[]
        for i in range(num_qubits):
            p.append(i)
        perm=permutations(p)

        with open(fname1) as fin, open(fname2,'w+') as fout:
            lines=fin.readlines()
            for i in range(x): 
               for line in lines:
                   for item in list(perm):
                        j = list(item)
                        line=line.replace('cx'+' '+str(j[1])+str(j[0])+' '+'cx'+' '+str(j[0])+str(j[2])+' '+'cx'+' '+str(j[1])+str(j[0]),'cx'+' '+str(j[0])+str(j[1])+' '+'cx'+' '+str(j[1])+str(j[2])+' '+'cx'+' '+str(j[0])+str(j[1]))
                        fout.write()
            fin.close()
            fout.close()
        return cost(fname2)
    def cx3to2cx(fname1,fname2,num_qubits):
        p=[]
        for i in range(num_qubits):
            p.append(i)
        perm=permutations(p)

        with open(fname1) as fin, open(fname2,'w+') as fout:
            lines=fin.readlines()
            for i in range(x): 
               for line in lines:
                   for item in list(perm):
                        j  = list(item):
                        line=line.replace('cx'+' '+str(j[0])+str(j[1])+' '+'cx'+' '+str(j[1])+str(j[2])+' '+'cx'+' '+str(j[0])+str(j[1]),'cx'+' '+str(j[0])+str(j[2])+' '+'cx'+' '+str(j[1])+str(j[2]))
                        fout.write()
            fin.close()
            fout.close()
        return cost(fname2)
    def cx3to3cx(fname1,fname2,num_qubits):
        p=[]
        for i in range(num_qubits):
            p.append(i)
        perm=permutations(p)

        with open(fname1) as fin, open(fname2,'w+') as fout:
            lines=fin.readlines()
            for i in range(x): 
               for line in lines:
                   for item in list(perm):
                        j  =list(item)
                        line=line.replace('cx'+' '+str(j[1])+str(j[2])+' '+'cx'+' '+str(j[0])+str(j[1])+' '+'cx'+' '+str(j[1])+str(j[2]),'cx'+' '+str(j[0])+str(j[2])+' '+'cx'+' '+str(j[0])+str(j[1]))

                        fout.write()
            fin.close()
            fout.close()
        return cost(fname2)
        
    def ticxij(fname1,fname2,num_qubits):
        p=[]
        for i in range(num_qubits):
            p.append(i)
        perm=permutations(p)

        with open(fname1) as fin, open(fname2,'w+') as fout:
            lines=fin.readlines()
            for i in range(x): 
               for line in lines:
                   for item in list(perm):
                       for j  in list(item):
                           line=line.replace('t'+' '+str(j[0])+' '+'cx'+' '+str(j[0])+str(j[1]),'cx'+' '+str(j[0])+str(j[1])+' '+'t'+' '+str(j[0]))
                           fout.write()
            fin.close()
            fout.close()
        return cost(fname2)
    def hh(fname1,fname2,num_qubits):
        p=[]
        for i in range(num_qubits):
            p.append(i)
        perm=permutations(p)

        with open(fname1) as fin, open(fname2,'w+') as fout:
            lines=fin.readlines()
            for i in range(x): 
               for line in lines:
                   for item in list(perm):
                       for j  in list(item):
                           line=line.replace('h'+' '+str(j[0])+' '+'h'+" "+str(j[0]),' ')
                           fout.write()
            fin.close()
            fout.close()
        return cost(fname2)
    def hxh(fname1,fname2,num_qubits):
        p=[]
        for i in range(num_qubits):
            p.append(i)
        perm=permutations(p)

        with open(fname1) as fin, open(fname2,'w+') as fout:
            lines=fin.readlines()
            for i in range(x): 
               for line in lines:
                   for item in list(perm):
                       for j  in list(item):
                           line=line.replace('h'+" "+str(j[0])+' '+ 'x'+' '+str(j[0])+' '+'h'+' '+str(j[0]),'h'+' '+str(j[0]))
                           fout.write()
            fin.close()
            fout.close()
        return cost(fname2)
    def tt(fname1,fname2,num_qubits):
        p=[]
        for i in range(num_qubits):
            p.append(i)
        perm=permutations(p)

        with open(fname1) as fin, open(fname2,'w+') as fout:
            lines=fin.readlines()
            for i in range(x): 
               for line in lines:
                   for item in list(perm):
                        j  = list(item)
                        line=line.replace('t'+' '+str(j[0])+'t'+" "+str(j[0]),'s'+" "+str(j[0]))
                        fout.write()
            fin.close()
            fout.close()
        return cost(fname2)
    def TT(fname1,fname2,num_qubits):
        p=[]
        for i in range(num_qubits):
            p.append(i)
        perm=permutations(p)

        with open(fname1) as fin, open(fname2,'w+') as fout:
            lines=fin.readlines()
            for i in range(x): 
               for line in lines:
                   for item in list(perm):
                        j  = list(item)
                        line=line.replace('T'+' '+str(j[0])+' '+'T'+" "+str(j[0]),'S'+' '+str(j[0]))
                        fout.write()
            fin.close()
            fout.close()
        return  cost(fname2)
    def SS(fname1,fname2,num_qubits):
        p=[]
        for i in range(num_qubits):
            p.append(i)
        perm=permutations(p)

        with open(fname1) as fin, open(fname2,'w+') as fout:
            lines=fin.readlines()
            for i in range(x): 
               for line in lines:
                   for item in list(perm):
                        j= list(item)
                        line=line.replace('s'+' '+str(j[0])+' '+'s'+" "+str(j[0]),'z'+" "+str(j[0]))
                        fout.write()
            fin.close()
            fout.close()
        return cost(fname2)
            
    def tT(fname1,fname2,num_qubits):
        p=[]
        for i in range(num_qubits):
            p.append(i)
        perm=permutations(p)

        with open(fname1) as fin, open(fname2,'w+') as fout:
            lines=fin.readlines()
            for i in range(x): 
               for line in lines:
                   for item in list(perm):
                       for j  in list(item):
                           line=line.replace('t'+' '+str(j[0])+' '+'T'+" "+str(j[0]),' ')
                           fout.write()
            fin.close()
            fout.close()
        return cost(fname2)
    def sS(fname1,fname2,num_qubits):
        p=[]
        for i in range(num_qubits):
            p.append(i)
        perm=permutations(p)

        with open(fname1) as fin, open(fname2,'w+') as fout:
            lines=fin.readlines()
            for i in range(x): 
               for line in lines:
                   for item in list(perm):
                       for j  in list(item):
                           line=line.replace('cx'+' '+str(j[0])+str(j[1])+' '+'h'+" "+str(j[0])+' '+'h'+' '+str(j[1])+' '+ 'cx'+' '+str(j[0])+str(j[1])+' '+'h'+" "+str(j[0])+' '+'h'+' '+str(j[1])+' '+'cx'+' '+str(j[0])+str(j[1])+' '+'h'+" "+str(j[0])+' '+'h'+' '+ str(j[1]),'cx'+' '+str(j[0])+str(j[1])+' '+'cx'+' '+str(j[1])+str(j[0])+' '+'cx'+' '+str(j[0])+str(j[1]))
                           fout.write()
            fin.close()
            fout.close()
     
        return cost(fname2)
    my_list={1:cxhhcx(),2:cxcx2to3(),3:cxcxcx(),5:ticxij(),6:cx3to2cx(),7:hh(),
    8:hxh(),9:tt(),10:TT(),11:tt(),12:SS(),13:tT(),14:sS(),15:cx3to3cx()}





     
    cost_pattern=[]
    p=[1,2,3,5,6,7,8,9,10,11,12,13,14,15]
    while (len(p)>0):
        perm=permutations(p)
        l=[]

        for item in list(perm):
            j = list(item)
            p=0
       
            for i in range(len(j)):
                pattern=my_list[j[i]]
                q=pattern(fname+str(i),fname+str(i+1))
                p=p+q
            l.append(p)
        min_index= l.index(min(l))   
        cost_pattern.append(list(perm)[min_index][0])         
        p.remove(list(perm)[min_index][0])   
             
    for i in range(len(cost_pattern)):
        pppp=my_list[cost_pattern[i]]
        pppp(fname+str(i),fname+str(i+1))
    p=inverse_parse_file(fname+str(len(cost_pattern)-1))


    return p<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.17207943562171737, 'fraction_numerical': 0.016533548808154892, 'mean_word_length': 1.8061393564140578, 'pattern_counts': {'":': 0, '<': 30, '<?xml version=': 0, '>': 32, 'https://': 2, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 1, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 12, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '6', 'dir': 'jupyter-structured-clean-dedup', 'id': '80624', 'license': 'MIT', 'n_tokens_mistral': 11673, 'n_tokens_neox': 11084, 'n_words': 2746, 'path': 'qosftask4(full).ipynb', 'repo_name': 'shamimmamun/qosftask4', 'size': '32213'}