Skip to content

Commit aff3efc

Browse files
authored
Improve inefficient string concatenation in clifford_tableu.py (#8044)
Replaced string concatenation using `+=` with list-based accumulation and a `"".join()` in `CliffordTableau.__str__()` and `_row_to_dense_pauli()`. This should improve performance from O(n^2) to O(n) for the string building operations in that function.
1 parent c40e01d commit aff3efc

1 file changed

Lines changed: 14 additions & 16 deletions

File tree

cirq-core/cirq/qis/clifford_tableau.py

Lines changed: 14 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -309,25 +309,23 @@ def __repr__(self) -> str:
309309
)
310310

311311
def __str__(self) -> str:
312-
string = ''
312+
words = []
313313

314314
for i in range(self.n, 2 * self.n):
315-
string += '- ' if self.rs[i] else '+ '
315+
words.append('- ' if self.rs[i] else '+ ')
316316

317317
for k in range(self.n):
318318
if self.xs[i, k] & (not self.zs[i, k]):
319-
string += 'X '
319+
words.append('X ')
320320
elif (not self.xs[i, k]) & self.zs[i, k]:
321-
string += 'Z '
321+
words.append('Z ')
322322
elif self.xs[i, k] & self.zs[i, k]:
323-
string += 'Y '
323+
words.append('Y ')
324324
else:
325-
string += 'I '
325+
words.append('I ')
326+
words.append('\n')
326327

327-
if i < 2 * self.n - 1:
328-
string += '\n'
329-
330-
return string
328+
return ''.join(words[:-1])
331329

332330
def _str_full_(self) -> str:
333331
left_col_width = max(7, self.n * 2 + 3)
@@ -499,18 +497,18 @@ def _row_to_dense_pauli(self, i: int) -> cirq.DensePauliString:
499497
from cirq.ops.dense_pauli_string import DensePauliString
500498

501499
coefficient = -1 if self.rs[i] else 1
502-
pauli_mask = ""
500+
pauli_mask = []
503501

504502
for k in range(self.n):
505503
if self.xs[i, k] & (not self.zs[i, k]):
506-
pauli_mask += "X"
504+
pauli_mask.append("X")
507505
elif (not self.xs[i, k]) & self.zs[i, k]:
508-
pauli_mask += "Z"
506+
pauli_mask.append("Z")
509507
elif self.xs[i, k] & self.zs[i, k]:
510-
pauli_mask += "Y"
508+
pauli_mask.append("Y")
511509
else:
512-
pauli_mask += "I"
513-
return DensePauliString(pauli_mask, coefficient=coefficient)
510+
pauli_mask.append("I")
511+
return DensePauliString("".join(pauli_mask), coefficient=coefficient)
514512

515513
def stabilizers(self) -> list[cirq.DensePauliString]:
516514
"""Returns the stabilizer generators of the state. These

0 commit comments

Comments
 (0)