Skip to content

Commit

Permalink
Add __iadd__ method to PauliSentence
Browse files Browse the repository at this point in the history
Signed-off-by: Anurav Modak <[email protected]>
  • Loading branch information
AnuravModak committed Oct 14, 2023
1 parent c1f9dfa commit 773ea74
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 0 deletions.
12 changes: 12 additions & 0 deletions pennylane/pauli/pauli_arithmetic.py
Original file line number Diff line number Diff line change
Expand Up @@ -342,6 +342,18 @@ def __add__(self, other):
larger_ps[key] += smaller_ps[key]

return larger_ps

Check notice on line 345 in pennylane/pauli/pauli_arithmetic.py

View check run for this annotation

codefactor.io / CodeFactor

pennylane/pauli/pauli_arithmetic.py#L345

Trailing whitespace (trailing-whitespace)
def __iadd__(self, other):
"""Adding two Pauli sentence together in-place by iterating over the smaller
one and adding its terms to the larger one, modifying self in place"""
smaller_ps, larger_ps = (self, other) if len(self) < len(other) else (other, self)

Check notice on line 349 in pennylane/pauli/pauli_arithmetic.py

View check run for this annotation

codefactor.io / CodeFactor

pennylane/pauli/pauli_arithmetic.py#L349

Unused variable 'larger_ps' (unused-variable)
for key in smaller_ps:
if key in self:
self[key]+=smaller_ps[key]
else:
self[key]=smaller_ps[key]

return self # Return self to indicate in-place modification

def __copy__(self):
"""Copy the PauliSentence instance."""
Expand Down
10 changes: 10 additions & 0 deletions tests/pauli/test_pauli_arithmetic.py
Original file line number Diff line number Diff line change
Expand Up @@ -409,6 +409,16 @@ def test_add(self, string1, string2, result):
(ps5, "Can't get the matrix of an empty PauliSentence."),
)

@pytest.mark.parametrize("string1, string2, result", tup_ps_add)
def test_iadd(self, string1, string2, result):
"""Test that the correct result of inplace-addition is produced."""
original_string2 = copy(string2)
string1 += string2 # Perform in-place addition using +=
string1.simplify()

assert string1 == result # Check if the modified object matches the expected result
assert original_string2 == string2 # Ensure the original object is not modified

@pytest.mark.parametrize("ps, match", ps_match)
def test_to_mat_error_empty(self, ps, match):
"""Test that an appropriate error is raised when an empty
Expand Down

0 comments on commit 773ea74

Please sign in to comment.