0
# Element Management
1
2
Core functionality for accessing, checking, and inspecting individual elements in multisets. Provides dictionary-like interface for element access and comprehensive methods for examining multiset contents.
3
4
## Capabilities
5
6
### Element Access and Membership
7
8
Access element multiplicities and test membership with dictionary-like interface.
9
10
```python { .api }
11
def __contains__(self, element) -> bool:
12
"""
13
Test if element is present in the multiset.
14
15
Parameters:
16
- element: Element to test for membership
17
18
Returns:
19
True if element has multiplicity > 0
20
"""
21
22
def __getitem__(self, element) -> int:
23
"""
24
Get the multiplicity of an element.
25
26
Parameters:
27
- element: Element to get multiplicity for
28
29
Returns:
30
Multiplicity of element (0 if not present)
31
"""
32
33
def get(self, element, default: int) -> int:
34
"""
35
Get the multiplicity of an element with optional default.
36
37
Parameters:
38
- element: Element to get multiplicity for
39
- default: Value to return if element not present
40
41
Returns:
42
Multiplicity of element or default value
43
"""
44
```
45
46
**Usage Examples:**
47
48
```python
49
from multiset import Multiset
50
51
ms = Multiset('aaabbc') # {'a': 3, 'b': 2, 'c': 1}
52
53
# Membership testing
54
'a' in ms # True
55
'z' in ms # False
56
57
# Get multiplicities
58
ms['a'] # 3
59
ms['z'] # 0 (not present)
60
ms.get('a') # 3
61
ms.get('z', -1) # -1 (using provided default)
62
```
63
64
### Collection Views and Iteration
65
66
Access different views of multiset contents for inspection and iteration.
67
68
```python { .api }
69
def distinct_elements(self) -> KeysView:
70
"""
71
Return a view of unique elements in the multiset.
72
73
Returns:
74
KeysView containing each unique element once
75
"""
76
77
def multiplicities(self) -> ValuesView:
78
"""
79
Return a view of all multiplicity values.
80
81
Returns:
82
ValuesView containing multiplicity of each unique element
83
"""
84
85
def values(self) -> ValuesView:
86
"""
87
Return a view of all multiplicity values (alias for multiplicities).
88
89
Returns:
90
ValuesView containing multiplicity of each unique element
91
"""
92
93
def items(self) -> ItemsView:
94
"""
95
Return a view of (element, multiplicity) pairs.
96
97
Returns:
98
ItemsView containing (element, multiplicity) tuples
99
"""
100
101
def __iter__(self) -> Iterator:
102
"""
103
Iterate over all elements with repetition based on multiplicity.
104
105
Returns:
106
Iterator yielding each element according to its multiplicity
107
"""
108
109
def __len__(self) -> int:
110
"""
111
Return total number of elements (sum of all multiplicities).
112
113
Returns:
114
Total count of elements including repetitions
115
"""
116
117
def __bool__(self) -> bool:
118
"""
119
Return True if multiset is non-empty.
120
121
Returns:
122
True if multiset contains any elements
123
"""
124
125
def from_elements(cls, elements, multiplicity: int):
126
"""
127
Create multiset where all elements have the same multiplicity.
128
129
Parameters:
130
- elements: Iterable of elements to include
131
- multiplicity: Multiplicity to assign to each element
132
133
Returns:
134
New multiset with uniform multiplicities
135
"""
136
137
def __copy__(self):
138
"""Support for copy.copy() - alias for copy() method."""
139
```
140
141
**Usage Examples:**
142
143
```python
144
ms = Multiset('aaabbc') # {'a': 3, 'b': 2, 'c': 1}
145
146
# View unique elements
147
list(ms.distinct_elements()) # ['a', 'b', 'c']
148
# View multiplicities
149
list(ms.multiplicities()) # [3, 2, 1]
150
# View multiplicities (alias)
151
list(ms.values()) # [3, 2, 1]
152
153
# View element-multiplicity pairs
154
list(ms.items()) # [('a', 3), ('b', 2), ('c', 1)]
155
156
# Iterate with repetition
157
list(ms) # ['a', 'a', 'a', 'b', 'b', 'c']
158
159
# Size and boolean tests
160
len(ms) # 6 (total elements)
161
bool(ms) # True (non-empty)
162
bool(Multiset()) # False (empty)
163
```
164
165
### String Representations
166
167
Get readable string representations of multiset contents.
168
169
```python { .api }
170
def __str__(self) -> str:
171
"""
172
Return string representation showing all elements with repetition.
173
174
Returns:
175
String containing all elements (like list representation)
176
"""
177
178
def __repr__(self) -> str:
179
"""
180
Return detailed string representation showing multiplicities.
181
182
Returns:
183
String showing constructor call with element-multiplicity mapping
184
"""
185
```
186
187
**Usage Examples:**
188
189
```python
190
ms = Multiset('aab')
191
192
str(ms) # "['a', 'a', 'b']"
193
repr(ms) # "Multiset({'a': 2, 'b': 1})"
194
print(ms) # ['a', 'a', 'b']
195
```
196
197
### Construction and Copying
198
199
Create new multisets and copies with various initialization patterns.
200
201
```python { .api }
202
def __init__(self, iterable = None):
203
"""
204
Initialize multiset from iterable or mapping.
205
206
Parameters:
207
- iterable: Optional iterable of elements or mapping of element->multiplicity
208
"""
209
210
def copy(self) -> BaseMultiset:
211
"""
212
Create a shallow copy of the multiset.
213
214
Returns:
215
New multiset with same elements and multiplicities
216
"""
217
218
def __copy__(self) -> BaseMultiset:
219
"""Support for copy.copy()."""
220
221
@classmethod
222
def from_elements(cls, elements, multiplicity: int):
223
"""
224
Create multiset where all elements have the same multiplicity.
225
226
Parameters:
227
- elements: Iterable of elements to include
228
- multiplicity: Multiplicity to assign to each element
229
230
Returns:
231
New multiset with uniform multiplicities
232
"""
233
```
234
235
**Usage Examples:**
236
237
```python
238
import copy
239
240
# Various construction methods
241
ms1 = Multiset('aab') # From string
242
ms2 = Multiset(['a', 'a', 'b']) # From list
243
ms3 = Multiset({'a': 2, 'b': 1}) # From mapping
244
ms4 = Multiset.from_elements('abc', 3) # All elements with count 3
245
246
# Copying
247
ms_copy = ms1.copy() # Explicit copy
248
ms_copy2 = copy.copy(ms1) # Using copy module (__copy__ method)
249
250
# Class method construction
251
ms4 = Multiset.from_elements('abc', 3) # All elements with count 3: {'a': 3, 'b': 3, 'c': 3}
252
253
# Verify independence
254
ms1.add('c')
255
ms_copy == ms1 # False (independent copies)
256
```
257
258
### Element Counting and Statistics
259
260
Additional utilities for analyzing multiset contents.
261
262
```python { .api }
263
def __len__(self) -> int:
264
"""Total number of elements (sum of multiplicities)."""
265
266
def __bool__(self) -> bool:
267
"""True if multiset contains any elements."""
268
```
269
270
**Usage Examples:**
271
272
```python
273
ms = Multiset('aaabbc')
274
275
# Basic statistics
276
len(ms) # 6 (total elements)
277
len(ms.distinct_elements()) # 3 (unique elements)
278
max(ms.multiplicities()) # 3 (highest multiplicity)
279
min(ms.multiplicities()) # 1 (lowest multiplicity)
280
sum(ms.multiplicities()) # 6 (same as len(ms))
281
282
# Check if empty
283
bool(Multiset()) # False
284
bool(ms) # True
285
```
286
287
### Serialization Support
288
289
Support for pickling multisets for persistence.
290
291
```python { .api }
292
def __getstate__(self):
293
"""Support for pickle serialization."""
294
295
def __setstate__(self, state):
296
"""Support for pickle deserialization."""
297
```
298
299
**Usage Examples:**
300
301
```python
302
import pickle
303
304
ms = Multiset('aab')
305
306
# Serialize and deserialize
307
data = pickle.dumps(ms)
308
ms_restored = pickle.loads(data)
309
310
ms == ms_restored # True (preserved contents)
311
```