Codebook: I.1 All about qubits: Problem 3

I have just started working my way through the Codebook.

The following code is being rejected with the error message shown. However, it executes as expected in Visual Studio Code.

I would be hugely grateful of someone could point out my error as it is not possible to progress in the codebook without rectifying the error.

{START}
def measure_state(state, num_meas):
“”"Simulate a quantum measurement process.

Args:
    state (array[complex]): A normalized qubit state vector. 
    num_meas (int): The number of measurements to take
    
Returns:
    array[int]: A set of num_meas samples, 0 or 1, chosen according to the probability 
    distribution defined by the input state.
"""

##################
# YOUR CODE HERE #
##################
Results = np.empty(num_meas, dtype=int)

# COMPUTE THE MEASUREMENT OUTCOME PROBABILITIES
Ket0Probability = np.real(state[0]*(state[0].conjugate())

# RETURN A LIST OF SAMPLE MEASUREMENT OUTCOMES
Results = np.random.choice(2, num_meas, p=[Ket0Probability, (1-Ket0Probability)])

return Results

state = np.array([0.8, 0.6])
num_meas = 10

print(measure_state(state,num_meas))
{END}

The error is “Error: invalid syntax (, line 20)”

Line 20 is the call to np.random.choice

I have tried Line 20 with “2” replaced with [0,1].

I have tried Line 20 dropping “p=”.

All four variants work in Visual Studio Code.

Thanks in advance,

Simon

Hi @SimonPRichards,
Welcome to the Xanadu community!
I think the invalid syntax refers to missing a “)” below.

Please try again with:
np.real(state[0]*(state[0].conjugate()))
Let me know if it worked.

Thank you so much - that was it!

I cant recall whether at some point I had the same error in Visual Studio Code and fixed it, but I was thrown as the incorrect line you pointed out is Line 18 and the error refers to Line 20.

I would never have found it.

Thanks again,

Simon

1 Like

Hi @SimonPRichards,
I’m happy to have helped!
If you have any other question just let us know!