Skip to content

Commit 5562852

Browse files
committed
add pop left and right for list
1 parent 2feb45e commit 5562852

File tree

3 files changed

+30
-0
lines changed

3 files changed

+30
-0
lines changed

forte/api/sparse_operator_list_api.cc

+2
Original file line numberDiff line numberDiff line change
@@ -148,6 +148,8 @@ void export_SparseOperatorList(py::module& m) {
148148
}
149149
})
150150
.def("reverse", &SparseOperatorList::reverse, "Reverse the order of the operators")
151+
.def("pop_left", &SparseOperatorList::pop_left, "Remove the leftmost operator")
152+
.def("pop_right", &SparseOperatorList::pop_right, "Remove the rightmost operator")
151153
.def(
152154
"__call__",
153155
[](const SparseOperatorList& op, const size_t n) {

forte/helpers/math_structures.h

+13
Original file line numberDiff line numberDiff line change
@@ -374,6 +374,19 @@ template <typename Derived, typename T, typename F> class VectorSpaceList {
374374
return it->second;
375375
}
376376

377+
/// @return a copy of the list with the leftmost element removed
378+
Derived pop_left() {
379+
assert(!elements_.empty());
380+
elements_.erase(elements_.begin());
381+
return static_cast<Derived&>(*this);
382+
}
383+
384+
/// @return a copy of the list with the rightmost element removed
385+
Derived pop_right() {
386+
assert(!elements_.empty());
387+
elements_.pop_back();
388+
return static_cast<Derived&>(*this);
389+
}
377390
/// @return the norm of the vector space
378391
/// @param p the norm to calculate (default is 2, -1 is infinity norm)
379392
double norm(int p = 2) const {

tests/pytest/sparse_ci/test_sparse_operator.py

+15
Original file line numberDiff line numberDiff line change
@@ -513,6 +513,7 @@ def test_sparse_operator_list_remove():
513513
sopl = forte.SparseOperatorList()
514514
sopl.add("[1a+ 1a-]", 1.0)
515515
sopl.add("[0a+ 0a-]", 1.0)
516+
sopl.add("[1a+ 1a-]", 1.0)
516517
sopl.remove("[1a+ 1a-]")
517518
assert len(sopl) == 1
518519

@@ -528,6 +529,19 @@ def test_sparse_operator_list_add():
528529
assert sop3(1)[0].str() == "[0a+ 0a-]"
529530

530531

532+
def test_sparse_operator_list_pop():
533+
sop = forte.SparseOperatorList()
534+
sop.add("[1a+ 1a-]", 1.0)
535+
sop.add("[0a+ 0a-]", 1.0)
536+
sop.add("[1a+ 1a-]", 1.0)
537+
assert len(sop) == 3
538+
sop = sop.pop_left()
539+
assert len(sop) == 2
540+
sop = sop.pop_right()
541+
assert len(sop) == 1
542+
assert sop(0)[0].str() == "[0a+ 0a-]"
543+
544+
531545
if __name__ == "__main__":
532546
test_sparse_operator_creation()
533547
test_sparse_operator()
@@ -536,3 +550,4 @@ def test_sparse_operator_list_add():
536550
test_sparse_operator_list_reverse()
537551
test_sparse_operator_list_remove()
538552
test_sparse_operator_list_add()
553+
test_sparse_operator_list_pop()

0 commit comments

Comments
 (0)