@@ -45,51 +45,107 @@ class _NotProvided:
45
45
pass
46
46
47
47
48
- class OrderedSet (AbstractSet [T ]):
48
+ from collections import defaultdict
49
+ from functools import partialmethod
50
+
51
+ class OrderedSet (dict , AbstractSet [T ]):
49
52
"""A set class that preserves insertion order.
50
53
51
54
It can be used as a drop-in replacement for :class:`set` where ordering is
52
55
desired.
53
56
"""
54
-
55
- def __init__ (self , items : Union [Iterable [T ], Type [_NotProvided ]] = _NotProvided )\
57
+ # def __new__(cls, *args: Any, **kwargs: Any)\
58
+ # -> None:
59
+ # """Create a new :class:`OrderedSet`, optionally initialized with *items*."""
60
+ # inst = super().__new__(cls)
61
+ # # inst.update(dict.fromkeys(*args, **kwargs))
62
+ # # inst = dict.fromkeys(*args, **kwargs)
63
+ # return inst
64
+ # super().__init__(None)
65
+ # if items is _NotProvided:
66
+ # self._dict = {}
67
+ # else:
68
+ # # type-ignore-reason:
69
+ # # mypy thinks 'items' can still be Type[_NotProvided] here.
70
+ # self._dict = dict.fromkeys(items)
71
+
72
+ def __init__ (self , * args : Any , ** kwargs : Any )\
56
73
-> None :
57
74
"""Create a new :class:`OrderedSet`, optionally initialized with *items*."""
58
- if items is _NotProvided :
59
- self ._dict = {}
60
- else :
75
+
76
+ # if items is _NotProvided:
77
+ # self = {}
78
+ # else:
61
79
# type-ignore-reason:
62
80
# mypy thinks 'items' can still be Type[_NotProvided] here.
63
- self ._dict = dict .fromkeys (items ) # type: ignore[arg-type]
81
+ if len (args ) > 1 :
82
+ raise TypeError
83
+ if args or kwargs :
84
+ super ().__init__ (dict .fromkeys (* args , ** kwargs )) # type: ignore[arg-type]
85
+ else :
86
+ super ().__init__ ()
87
+ # print(self, list(self))
88
+
89
+ add = dict .setdefault
90
+ remove = dict .pop
91
+ # __eq__ = frozenset.__ eq__
92
+
93
+ pop = lambda self : self .popitem ()[0 ]
94
+ # union = dict.__ior__
95
+ # update = dict.update
96
+ # isdisjoint = partialmethod(frozenset.isdisjoint, self.keys())
97
+
98
+ # list = dict.list
99
+
100
+ # def add(self, element: T) -> None:
101
+ # """Add *element* to this set."""
102
+ # self._dict = {**self._dict, **{element: None}}
103
+
104
+ # __init__ = None
105
+ # __init__ = dict.fromkeys
106
+
107
+ # def __init__(self, items: Union[Iterable[T], Type[_NotProvided]] = _NotProvided)\
108
+ # -> None:
109
+ # """Create a new :class:`OrderedSet`, optionally initialized with *items*."""
110
+ # if items is _NotProvided:
111
+ # self._dict = {}
112
+ # else:
113
+ # # type-ignore-reason:
114
+ # # mypy thinks 'items' can still be Type[_NotProvided] here.
115
+ # self._dict = dict.fromkeys(items) # type: ignore[arg-type]
64
116
65
117
def __eq__ (self , other : object ) -> bool :
66
118
"""Return whether this set is equal to *other*."""
67
- return (isinstance (other , Set )
68
- and len (self ) == len (other )
69
- and all (i in other for i in self ))
119
+ return self .keys () == other
70
120
71
121
def __repr__ (self ) -> str :
72
122
"""Return a string representation of this set."""
73
123
if len (self ) == 0 :
74
124
return "OrderedSet()"
75
- return "OrderedSet({" + ", " .join ([repr (k ) for k in self . _dict ]) + "})"
125
+ return "OrderedSet({" + ", " .join ([repr (k ) for k in self ]) + "})"
76
126
77
- def add (self , element : T ) -> None :
78
- """Add *element* to this set."""
79
- self ._dict = {** self ._dict , ** {element : None }}
127
+ # def add(self, element: T) -> None:
128
+ # """Add *element* to this set."""
129
+ # self._dict = {**self._dict, **{element: None}}
80
130
81
- def clear (self ) -> None :
82
- """Remove all elements from this set."""
83
- self ._dict .clear ()
131
+ # def clear(self) -> None:
132
+ # """Remove all elements from this set."""
133
+ # self._dict.clear()
134
+
135
+ def discard (self , element : T ) -> None :
136
+ """Remove *element* from this set if it is present."""
137
+ if element in self :
138
+ del self [element ]
139
+ # self.pop(element, None)
84
140
85
141
def copy (self ) -> OrderedSet [T ]:
86
142
"""Return a shallow copy of this set."""
87
- return OrderedSet (self . _dict . copy () )
143
+ return OrderedSet (self )
88
144
89
145
def difference (self , * others : Iterable [T ]) -> OrderedSet [T ]:
90
146
"""Return all elements that are in this set but not in *others*."""
91
147
if not others :
92
- return OrderedSet (self . _dict )
148
+ return OrderedSet (self )
93
149
other_elems = set .union (* map (set , others ))
94
150
items = {item : None for item in self if item not in other_elems }
95
151
return OrderedSet (items )
@@ -100,18 +156,13 @@ def difference_update(self, *others: Iterable[T]) -> None:
100
156
for e in other :
101
157
self .discard (e )
102
158
103
- def discard (self , element : T ) -> None :
104
- """Remove *element* from this set, if it is present."""
105
- if element in self ._dict :
106
- del self ._dict [element ]
107
-
108
159
def intersection (self , * others : Iterable [T ]) -> OrderedSet [T ]:
109
160
"""Return the intersection of this set and *others*."""
110
161
if not others :
111
- return OrderedSet (self . _dict )
162
+ return OrderedSet (self )
112
163
113
164
result_elements = []
114
- for element in self ._dict . keys ():
165
+ for element in self .keys ():
115
166
if all (element in other for other in others ):
116
167
result_elements .append (element )
117
168
@@ -122,105 +173,111 @@ def intersection_update(self, *others: Iterable[T]) -> None:
122
173
if not others :
123
174
return
124
175
125
- common_keys = list ( self ._dict . keys () )
176
+ common_keys = self .keys ()
126
177
for other in others :
127
- common_keys = [key for key in common_keys if key in set ( other ) ]
178
+ common_keys = [key for key in common_keys if key in other ]
128
179
129
- self ._dict = dict .fromkeys (common_keys )
180
+ self .clear ()
181
+ self .update (common_keys )
130
182
131
183
def isdisjoint (self , s : Iterable [T ]) -> bool :
132
184
"""Return whether this set is disjoint with *s*."""
133
- return self ._dict . keys ().isdisjoint (s )
185
+ return self .keys ().isdisjoint (s )
134
186
135
187
def issubset (self , s : Iterable [T ]) -> bool :
136
188
"""Return whether this set is a subset of *s*."""
137
- return all ( i in s for i in self )
189
+ return set ( self ). issubset ( s )
138
190
139
191
def issuperset (self , s : Iterable [T ]) -> bool :
140
192
"""Return whether this set is a superset of *s*."""
141
193
return set (self ).issuperset (set (s ))
142
194
143
- def pop (self ) -> T :
144
- """Remove and return the most recently added element from this set."""
145
- items = list (self ._dict )
146
- result = items .pop ()
147
- self ._dict = dict .fromkeys (items )
148
- return result
195
+ # def pop(self) -> T:
196
+ # """Remove and return the most recently added element from this set."""
197
+ # items = list(self._dict)
198
+ # result = items.pop()
199
+ # self._dict = dict.fromkeys(items)
200
+ # return result
149
201
150
- def remove (self , element : T ) -> None :
151
- """Remove *element* from this set, raising :exc:`KeyError` if not present."""
152
- del self ._dict [element ]
202
+ # def remove(self, element: T) -> None:
203
+ # """Remove *element* from this set, raising :exc:`KeyError` if not present."""
204
+ # del self._dict[element]
153
205
154
206
def symmetric_difference (self , s : Iterable [T ]) -> OrderedSet [T ]:
155
207
"""Return the symmetric difference of this set and *s*."""
156
208
return OrderedSet (
157
- dict .fromkeys ([e for e in self . _dict if e not in s ]
158
- + [e for e in s if e not in self . _dict ]))
209
+ dict .fromkeys ([e for e in self if e not in s ]
210
+ + [e for e in s if e not in self ]))
159
211
160
212
def symmetric_difference_update (self , s : Iterable [T ]) -> None :
161
213
"""Update this set to be the symmetric difference of itself and *s*."""
162
- self ._dict = self .symmetric_difference (s )._dict
214
+ x = self .symmetric_difference (s )
215
+ self .clear ()
216
+ self .update (x )
163
217
164
218
def union (self , * others : Iterable [T ]) -> OrderedSet [T ]:
165
219
"""Return the union of this set and *others*."""
166
- return OrderedSet (list (self . _dict )
220
+ return OrderedSet (list (self )
167
221
+ [e for other in others for e in other ])
168
222
169
223
def update (self , * others : Iterable [T ]) -> None :
170
224
"""Update this set to be the union of itself and *others*."""
171
- self ._dict = self .union (* others )._dict
225
+ x = self | dict .fromkeys (* others )
226
+ self .clear ()
227
+ for e in x :
228
+ self .add (e )
172
229
173
- def __len__ (self ) -> int :
174
- """Return the number of elements in this set."""
175
- return len (self ._dict )
230
+ # def __len__(self) -> int:
231
+ # """Return the number of elements in this set."""
232
+ # return len(self._dict)
176
233
177
- def __contains__ (self , o : object ) -> bool :
178
- """Return whether *o* is in this set."""
179
- return o in self ._dict
234
+ # def __contains__(self, o: object) -> bool:
235
+ # """Return whether *o* is in this set."""
236
+ # return o in self._dict
180
237
181
- def __iter__ (self ) -> Iterator [T ]:
182
- """Return an iterator over the elements of this set."""
183
- return iter (self ._dict )
238
+ # def __iter__(self) -> Iterator[T]:
239
+ # """Return an iterator over the elements of this set."""
240
+ # return iter(self._dict)
184
241
185
242
def __and__ (self , s : Set [T ]) -> OrderedSet [T ]:
186
243
"""Return the intersection of this set and *s*."""
187
244
return self .intersection (s )
188
245
189
- def __iand__ (self , s : Set [T ]) -> OrderedSet [T ]:
190
- """Update this set to be the intersection of itself and *s*."""
191
- result = self .intersection (s )
192
- self ._dict = result ._dict
193
- return result
246
+ # def __iand__(self, s: Set[T]) -> OrderedSet[T]:
247
+ # """Update this set to be the intersection of itself and *s*."""
248
+ # result = self.intersection(s)
249
+ # self._dict = result._dict
250
+ # return result
194
251
195
252
def __or__ (self , s : Set [Any ]) -> OrderedSet [T ]:
196
253
"""Return the union of this set and *s*."""
197
254
return self .union (s )
198
255
199
- def __ior__ (self , s : Set [Any ]) -> OrderedSet [T ]:
200
- """Update this set to be the union of itself and *s*."""
201
- result = self .union (s )
202
- self ._dict = result ._dict
203
- return result
256
+ # def __ior__(self, s: Set[Any]) -> OrderedSet[T]:
257
+ # """Update this set to be the union of itself and *s*."""
258
+ # result = self.union(s)
259
+ # self._dict = result._dict
260
+ # return result
204
261
205
- def __sub__ (self , s : Set [T ]) -> OrderedSet [T ]:
206
- """Return the difference of this set and *s*."""
207
- return self .difference (s )
262
+ # def __sub__(self, s: Set[T]) -> OrderedSet[T]:
263
+ # """Return the difference of this set and *s*."""
264
+ # return self.difference(s)
208
265
209
- def __isub__ (self , s : Set [T ]) -> OrderedSet [T ]:
210
- """Update this set to be the difference of itself and *s*."""
211
- result = self .difference (s )
212
- self ._dict = result ._dict
213
- return result
266
+ # def __isub__(self, s: Set[T]) -> OrderedSet[T]:
267
+ # """Update this set to be the difference of itself and *s*."""
268
+ # result = self.difference(s)
269
+ # self._dict = result._dict
270
+ # return result
214
271
215
- def __xor__ (self , s : Set [Any ]) -> OrderedSet [T ]:
216
- """Return the symmetric difference of this set and *s*."""
217
- return self .symmetric_difference (s )
272
+ # def __xor__(self, s: Set[Any]) -> OrderedSet[T]:
273
+ # """Return the symmetric difference of this set and *s*."""
274
+ # return self.symmetric_difference(s)
218
275
219
- def __ixor__ (self , s : Set [Any ]) -> OrderedSet [T ]:
220
- """Update this set to be the symmetric difference of itself and *s*."""
221
- result = self .symmetric_difference (s )
222
- self ._dict = result ._dict
223
- return result
276
+ # def __ixor__(self, s: Set[Any]) -> OrderedSet[T]:
277
+ # """Update this set to be the symmetric difference of itself and *s*."""
278
+ # result = self.symmetric_difference(s)
279
+ # self._dict = result._dict
280
+ # return result
224
281
225
282
def __le__ (self , s : Set [T ]) -> bool :
226
283
"""Return whether this set is a subset of *s*."""
@@ -272,7 +329,7 @@ def __hash__(self) -> int:
272
329
if self ._my_hash :
273
330
return self ._my_hash
274
331
275
- self ._my_hash = hash (frozenset (self ))
332
+ self ._my_hash = hash (frozenset (self . _dict ))
276
333
return self ._my_hash
277
334
278
335
def __eq__ (self , other : object ) -> bool :
0 commit comments