I would recommend reading this article:
Effient quantum algorithms for GHZ and W states, and implementation on the IBM Q.
It provides general algorithm for constructing a circuit producing W-state with arbitrary number of qubits.
Here is a code based on the article:
def _w_state_circuit(circuit, nn, mm, qubitC):
global qubitT #reference to global variable qubitT
if nn == 0 and mm == 1:
pass #do nothing in this case
elif nn == 1 and mm == 2: #case (1,2)
circuit.cu3(m.pi/2, 0, 0, q[qubitC], q[qubitT])
circuit.cx(q[qubitT], q[qubitC])
qubitT = qubitT + 1
else: #otherwise
theta = 2*np.arccos(m.sqrt(nn/mm))
circuit.cu3(theta, 0, 0, q[qubitC], q[qubitT])
circuit.cx(q[qubitT], q[qubitC])
qubitTRecurse = qubitT #saving target qubit index, used as control qubit for lower child
qubitT = qubitT + 1
a = m.floor(nn/2)
b = m.floor(mm/2)
c = m.ceil(nn/2)
d = m.ceil(mm/2)
if a == 1 and b == 1: #upper child (1,1) => (1,2) became upper child
circuit = _w_state_circuit(circuit, 1, 2, qubitC)
#there is no lower child
elif c == 1 and d == 1: #lower child (1,1) => (1,2) became lower child
circuit = _w_state_circuit(circuit, 1, 2, qubitTRecurse)
#there is no upper child
else:
#upper child
circuit = _w_state_circuit(circuit, a, b, qubitC)
#lower child
circuit = _w_state_circuit(circuit, c, d, qubitTRecurse)
return circuit
def w_state_circuit (qubits, qRegister, cRegister):
global qubitT
qubitT = 1 #index of a qubit a new gate acts on (hard to compute inside recursion => global variable)
circuit = QuantumCircuit(qRegister, cRegister)
circuit.x(q[0])
circuit = _w_state_circuit(circuit, m.floor(qubits/2), qubits, 0)
return circuit
#construction of 6 qubits W-state
qubits = 6
q = QuantumRegister(qubits, name = 'q')
c = ClassicalRegister(qubits, name = 'c')
circuit = w_state_circuit(qubits, q, c)
circuit.draw()