Skip to content

Commit 3f35447

Browse files
committed
-
1 parent 361b6ba commit 3f35447

File tree

3 files changed

+61
-0
lines changed

3 files changed

+61
-0
lines changed
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
# Copyright 2009-2014 Ram Rachum.
2+
# This program is distributed under the MIT license.
3+
4+
'''Defines various tools related to data structures.'''
5+
6+
import collections
7+
import itertools
8+
import numbers
9+
10+
from python_toolbox import nifty_collections
11+
12+
13+
@nifty_collections.LazyTuple.factory
14+
def get_all_contained_counters(counter):
15+
assert isinstance(counter, collections.Counter)
16+
counter_type = type(counter)
17+
keys, amounts = zip(
18+
*((key, amount) for key, amount in counter.items() if amount)
19+
)
20+
assert all(isinstance(amount, numbers.Integral) for amount in amounts)
21+
amounts_tuples = \
22+
itertools.product(*map(lambda amount: xrange(amount+1), amounts))
23+
for amounts_tuple in amounts_tuples:
24+
yield counter_type(dict(zip(keys, amounts_tuple)))

source_py2/test_python_toolbox/test_collection_tools/__init__.py

Whitespace-only changes.
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
# Copyright 2009-2014 Ram Rachum.
2+
# This program is distributed under the MIT license.
3+
4+
import collections
5+
6+
from python_toolbox import nifty_collections
7+
8+
from python_toolbox import collection_tools
9+
10+
11+
def test():
12+
13+
counter = collections.Counter('abracadabra')
14+
assert counter == collections.Counter({'a': 5, 'b': 2, 'r': 2, 'c': 1,
15+
'd': 1,})
16+
all_contained_counters = \
17+
collection_tools.get_all_contained_counters(counter)
18+
19+
assert isinstance(all_contained_counters, nifty_collections.LazyTuple)
20+
21+
assert not all_contained_counters.collected_data
22+
23+
# Now we'll exhaust `all_contained_counters`:
24+
assert len(all_contained_counters) == 6 * 3 * 3 * 2 * 2
25+
assert all_contained_counters.exhausted
26+
27+
assert counter in all_contained_counters
28+
assert collections.Counter({'a': 0, 'b': 0, 'r': 0, 'c': 0, 'd': 0,}) in \
29+
all_contained_counters
30+
assert collections.Counter({'a': 1, 'b': 1, 'r': 1, 'c': 1, 'd': 1,}) in \
31+
all_contained_counters
32+
assert collections.Counter({'a': 2, 'b': 2, 'r': 2, 'c': 1, 'd': 1,}) in \
33+
all_contained_counters
34+
assert collections.Counter({'a': 4, 'b': 2, 'r': 2, 'c': 1, 'd': 1,}) in \
35+
all_contained_counters
36+
assert all(isinstance(item, collections.Counter) for item in
37+
all_contained_counters)

0 commit comments

Comments
 (0)