Anonymous user
Set consolidation: Difference between revisions
→{{header|Python}}: Separate testing function.
(Added F# version) |
(→{{header|Python}}: Separate testing function.) |
||
Line 943:
=={{header|Python}}==
===Python: Iterative===
The docstring contains solutions to all the examples as well as a check to show the order-independence of the sets given to the consolidate function.▼
<lang python>def consolidate(sets):
'''▼
>>> # Define some variables▼
>>> A,B,C,D,E,F,G,H,I,J,K = 'A,B,C,D,E,F,G,H,I,J,K'.split(',')▼
>>> # Consolidate some lists of sets▼
>>> consolidate([{A,B}, {C,D}])▼
>>> consolidate([{A,B}, {B,D}])▼
>>> consolidate([{A,B}, {C,D}, {D,B}])▼
>>> consolidate([{H,I,K}, {A,B}, {C,D}, {D,B}, {F,G,H}])▼
[{'A', 'C', 'B', 'D'}, {'G', 'F', 'I', 'H', 'K'}]▼
>>> consolidate([{A,H}, {H,I,K}, {A,B}, {C,D}, {D,B}, {F,G,H}])▼
[{'A', 'C', 'B', 'D', 'G', 'F', 'I', 'H', 'K'}]▼
>>> consolidate([{H,I,K}, {A,B}, {C,D}, {D,B}, {F,G,H}, {A,H}])▼
[{'A', 'C', 'B', 'D', 'G', 'F', 'I', 'H', 'K'}]▼
>>> # Confirm order-independence▼
>>> from copy import deepcopy▼
>>> import itertools▼
>>> answer = consolidate(deepcopy(sets))▼
>>> for perm in itertools.permutations(sets):▼
[{'A', 'C', 'B', 'D', 'G', 'F', 'I', 'H', 'K'}]▼
>>> len(list(itertools.permutations(sets)))▼
720▼
setlist = [s for s in sets if s]
for i, s1 in enumerate(setlist):
Line 988 ⟶ 956:
return [s for s in setlist if s]</lang>
===Python: Recursive===
<lang python>def conso(s):
if len(s) < 2: return s
Line 997 ⟶ 965:
else: r.append(x)
return r</lang>
===Python: Testing===
▲The
<lang python>def _test(consolidate=consolidate):
def freze(list_of_sets):
'return a set of frozensets from the list of sets to allow comparison'
return set(frozenset(s) for s in list_of_sets)
assert (freze(consolidate([{A,B}, {C,D}])) == freze([{'A', 'B'}, {'C', 'D'}]))
assert (freze(consolidate([{A,B}, {B,D}])) == freze([{'A', 'B', 'D'}]))
assert (freze(consolidate([{A,B}, {C,D}, {D,B}])) == freze([{'A', 'C', 'B', 'D'}]))
▲ freze([{'A', 'C', 'B', 'D'}, {'G', 'F', 'I', 'H', 'K'}]))
▲ freze([{'A', 'C', 'B', 'D', 'G', 'F', 'I', 'H', 'K'}]))
▲ freze([{'A', 'C', 'B', 'D', 'G', 'F', 'I', 'H', 'K'}]))
▲ assert (answer == [{'A', 'C', 'B', 'D', 'G', 'F', 'I', 'H', 'K'}])
print('_test(%s) complete' % consolidate.__name__)
if __name__ == '__main__':
_test(conso)</lang>
{{out}}
<pre>_test(consolidate) complete
_test(conso) complete</pre>
=={{header|Racket}}==
|