/
listtools.py
76 lines (63 loc) · 2.57 KB
/
listtools.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
from __future__ import division, print_function, absolute_import, unicode_literals
#*****************************************************************
# pyGSTi 0.9: Copyright 2015 Sandia Corporation
# This Software is released under the GPL license detailed
# in the file "license.txt" in the top-level pyGSTi directory
#*****************************************************************
""" Utility functions for working with lists """
def remove_duplicates_in_place(l,indexToTest=None):
"""
Remove duplicates from the list passed as an argument.
In the special case when l contains WeightedGateString instances, the
duplicates are removed in such a way that the largest weight instance
of any set of duplicates is kept.
Parameters
----------
l : list
The list to remove duplicates from.
indexToTest : int, optional
If not None, the index within the elements of l to test. For
example, if all the elements of l contain 2 tuples (x,y) then
set indexToTest == 1 to remove tuples with duplicate y-values.
Returns
-------
None
"""
s = set(); n = 0
for x in l:
t = x if indexToTest is None else x[indexToTest]
#TODO: create a special duplicate removal function for use with
# WeighedGateStrings and include the below commented block:
#Special case of weighted gate strings: if collisions
# keep the hightest weight string
#if isinstance(t, _WeightedGateString) and t in s:
# for gs in l[0:n]:
# if gs == t:
# if isinstance(gs, _WeightedGateString):
# gs.weight = max(gs.weight, t.weight)
# break
if t not in s:
s.add(t)
l[n] = x; n += 1
del l[n:]
def remove_duplicates(l,indexToTest=None):
"""
Remove duplicates from the a list and return the result.
In the special case when l contains WeightedGateString instances, the
duplicates are removed in such a way that the largest weight instance
of any set of duplicates is kept.
Parameters
----------
l : list
The list to remove duplicates from.
indexToTest : int, optional
If not None, the index within the elements of l to test. For
example, if all the elements of l contain 2 tuples (x,y) then
set indexToTest == 1 to remove tuples with duplicate y-values.
Returns
-------
list
the list after duplicates have been removed.
"""
lcopy = l[:]; remove_duplicates_in_place(lcopy,indexToTest)
return lcopy