Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add __iadd__ method to PauliSentence #4662

Merged
merged 14 commits into from
Oct 30, 2023
9 changes: 9 additions & 0 deletions pennylane/pauli/pauli_arithmetic.py
Original file line number Diff line number Diff line change
Expand Up @@ -342,6 +342,15 @@
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)
AnuravModak marked this conversation as resolved.
Show resolved Hide resolved
def __iadd__(self, other):
AnuravModak marked this conversation as resolved.
Show resolved Hide resolved
"""Inplace addition of two Pauli sentence together by adding terms of other to self"""
for key in other:
if key in self:
self[key] += other[key]
else:
self[key] = other[key]
return self

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 and other object is not changed."""
original_string2=copy(string2)
AnuravModak marked this conversation as resolved.
Show resolved Hide resolved
string1 += string2
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
Loading