Zohim Chandani
Zohim Chandani

Reputation: 29

How do I iterate over string?

I have code that looks like this

'''

phi = (QubitOperator('X0') + 
       QubitOperator('Y0') +
       QubitOperator('Z0') + 
       QubitOperator('X1') +
       QubitOperator('Y1') +
       QubitOperator('Z1') )

'''

where QubitOperator is a command in a package I am using. How can I automate this to iterate over X Y and Z and 0, 1, 2.... and create phi?

Upvotes: -2

Views: 64

Answers (1)

Hikash
Hikash

Reputation: 429

your existing code may be cleaner, but supposing you had to do this for more than 8 elements:

from functools import reduce

letters = ['X', 'Y', 'Z']
numbers = ['0', '1', '2']
pairs = [f'{l}{n}' for l in letters for n in numbers]
# this gets you ['X0', 'X1', 'X2', 'Y0', ..., 'Z2']
qubits = [QubitOperator(x) for x in pairs]
# not sure the best way to get this into a single phi. join seems logical, but probably doesn't work.
phi = reduce(lambda acc, cur: acc + cur, pairs)

Overview of the code:

  1. The first three lines basically just define the data and merge them together. the list comprehension is kind of 2-layered (unofficial term), so it'll iterate over letters, then iterate over numbers until all 9 elements are reached
  2. line 4 (beginning qubits = [... wraps each of the strings created in pairs inside a QubitOperator. Technically not needed, and I'd probably put it in line 3 if I were coding for myself.
  3. Line 5, as noted, is not necessarily the best way of doing this, but it was the best I could think of. reduce basically allows you to compress a list of stuff into something else -- in this case, we're going to concatenate everything into phi. This will iterate over the list of qubits and add them together. Expanding this out gets something close to what you've already done: QubitOperator('X0') + QubitOperator('X1')+... As a commenter pointed out, a for loop may work as well in this scenario. That code looks like:
phi = qubits[0]
for i in range(1, len(qubits)):
  phi = phi + qubits[i]

There is a caveat here: I'm not 100 percent sure this is going to work. Every step prior to the last one should, and I think the last step should as well, but without any testing, it's hard to know.

Also, as you can see, we effectively turned 8 lines of straight forward code into 4 lines of relatively complex code. I'm not sure that tradeoff is worth it, unless you have a lot of data, or otherwise you need to repeat this process frequently with fresh data.

Upvotes: 0

Related Questions