Esempio n. 1
0
    def test_helper_function(self):
        # two paths, one for real dicts and one for other mappings
        elems = list('abracadabra')

        d = dict()
        _count_elements(d, elems)
        self.assertEqual(d, {'a': 5, 'r': 2, 'b': 2, 'c': 1, 'd': 1})

        m = OrderedDict()
        _count_elements(m, elems)
        self.assertEqual(m,
             OrderedDict([('a', 5), ('b', 2), ('r', 2), ('c', 1), ('d', 1)]))
Esempio n. 2
0
def rand_sock(n):
    sock_style = ['ankle', 'crew', 'calf', 'thigh']
    sock_list = []
    i = 0
    while i < n:
        socks = random.choice(sock_style)
        sock_list.append(socks)
        i += 1
    #print(sock_list)
    sock_count = {}
    _count_elements(sock_count, sock_list)
    return sock_count
Esempio n. 3
0
    def test_helper_function(self):
        # two paths, one for real dicts and one for other mappings
        elems = list('abracadabra')

        d = dict()
        _count_elements(d, elems)
        self.assertEqual(d, {'a': 5, 'r': 2, 'b': 2, 'c': 1, 'd': 1})

        m = OrderedDict()
        _count_elements(m, elems)
        self.assertEqual(
            m, OrderedDict([('a', 5), ('b', 2), ('r', 2), ('c', 1), ('d', 1)]))
Esempio n. 4
0
def profile_data(rows,
                 header=None,
                 top=10,
                 na_val=[None, "", "N/A", "NULL", "null", "none", "na"]):
    result = {}

    rec = None
    col = []

    if isinstance(header, int):
        if hasattr(rows, "__next__"):
            for i in range(header + 1):
                col = next(rows)
        else:
            col, *rows = rows[header:]
    elif isinstance(header, (list, tuple)):
        col = header

    for i, x in enumerate(zip_longest(*rows)):
        if rec is None:
            rec = len(x)

        counter = {}
        gc = counter.get

        _count_elements(counter, [y for y in x if y not in na_val])

        uq_n = len(counter)
        uq_rate = uq_n / rec

        notna_n = sum(counter.values())

        topN = heapq.nlargest(top, counter, key=gc) if top > 0 else []

        del counter, gc

        na_n = rec - notna_n
        fill_rate = notna_n / rec
        if uq_rate > 0 and fill_rate > 0:
            key_rate = (uq_rate * fill_rate) / (
                (pow(uq_rate, 2) + pow(fill_rate, 2))**0.5)
        else:
            key_rate = 0.0

        info = ret(rec, rec == notna_n, rec == uq_n, notna_n, na_n, uq_n,
                   fill_rate, uq_rate, key_rate, topN)

        k = col[i] if i < len(col) else i

        result[k] = info

    return result
Esempio n. 5
0
def part_one(list_of_ids):
    '''
    Question:
        What is the checksum for your list of box IDs?

    Produces a checksum by multiplying how many of IDs contains a letter which appears twice and three times.
    '''

    ntimes = {2: 0, 3: 0}
    for id_ in list_of_ids:
        letter_ntimes = {}
        collections._count_elements(letter_ntimes, id_)
        ntimes_set = set(list(letter_ntimes.values()))
        ntimes_set.discard(1)
        collections._count_elements(ntimes, ntimes_set)
    checksum = ntimes[2] * ntimes[3]
    return checksum
Esempio n. 6
0
def rand_sock_style_color(n):
    sock_style = ['ankle', 'crew', 'calf', 'thigh']
    sock_colors = ['black', 'white', 'blue']
    tuple_list = []
    i = 0
    while i < n:
        socks = random.choice(sock_style)
        colors = random.choice(sock_colors)
        sock_tuple = (socks, colors)
        tuple_list.append(sock_tuple)
        i += 1

    #print(tuple_list)
    style_color_count = {}
    _count_elements(style_color_count, tuple_list)
    for key in style_color_count:
        value = style_color_count[key]//2
        style_color_count[key] = value
    return(style_color_count)
Esempio n. 7
0
    def update(*args, **kwds):
        """Like dict.update() but add counts instead of replacing them.

        Source can be an iterable, a dictionary, or another Counter instance.

        >>> c = Counter('which')
        >>> c.update('witch')           # add elements from another iterable
        >>> d = Counter('watch')
        >>> c.update(d)                 # add elements from another counter
        >>> c['h']                      # four 'h' in which, witch, and watch
        4

        """
        # The regular dict.update() operation makes no sense here because the
        # replace behavior results in the some of original untouched counts
        # being mixed-in with all of the other counts for a mismash that
        # doesn't have a straight-forward interpretation in most counting
        # contexts.  Instead, we implement straight-addition.  Both the inputs
        # and outputs are allowed to contain zero and negative counts.

        if not args:
            raise TypeError(
                "descriptor 'update' of 'Counter' object " "needs an argument"
            )
        self = args[0]
        args = args[1:]
        if len(args) > 1:
            raise TypeError("expected at most 1 arguments, got %d" % len(args))
        iterable = args[0] if args else None
        if iterable is not None:
            if isinstance(iterable, Mapping):
                if self:
                    self_get = self.get
                    for elem, count in iterable.items():
                        self[elem] = count + self_get(elem, 0)
                else:
                    super(Counter, self).update(
                        iterable
                    )  # fast path when counter is empty
            else:
                _count_elements(self, iterable)
        if kwds:
            self.update(kwds)
Esempio n. 8
0
 def update(*args, **kwds):
     if not args:
         raise TypeError("descriptor 'update' of 'Counter' object "
                         "needs an argument")
     self, *args = args
     if len(args) > 1:
         raise TypeError('expected at most 1 arguments, got %d' % len(args))
     iterable = args[0] if args else None
     if iterable is not None:
         if isinstance(iterable, collections.Mapping):
             if self:
                 self_get = self.get
                 for elem, count in iterable.items():
                     self[elem] = count + self_get(elem, 0)
             else:
                 super(UserCounterBase, self).update(
                     iterable)  # fast path when counter is empty
         else:
             _count_elements(self, iterable)
     if kwds:
         self.update(kwds)
Esempio n. 9
0
    def update(*args, **kwds):
        '''Like dict.update() but add counts instead of replacing them.

        Source can be an iterable, a dictionary, or another Counter instance.

        >>> c = Counter('which')
        >>> c.update('witch')           # add elements from another iterable
        >>> d = Counter('watch')
        >>> c.update(d)                 # add elements from another counter
        >>> c['h']                      # four 'h' in which, witch, and watch
        4

        '''
        # The regular dict.update() operation makes no sense here because the
        # replace behavior results in the some of original untouched counts
        # being mixed-in with all of the other counts for a mismash that
        # doesn't have a straight-forward interpretation in most counting
        # contexts.  Instead, we implement straight-addition.  Both the inputs
        # and outputs are allowed to contain zero and negative counts.

        if not args:
            raise TypeError("descriptor 'update' of 'Counter' object "
                            "needs an argument")
        self = args[0]
        args = args[1:]
        if len(args) > 1:
            raise TypeError('expected at most 1 arguments, got %d' % len(args))
        iterable = args[0] if args else None
        if iterable is not None:
            if isinstance(iterable, Mapping):
                if self:
                    self_get = self.get
                    for elem, count in iterable.items():
                        self[elem] = count + self_get(elem, 0)
                else:
                    super(Counter, self).update(iterable) # fast path when counter is empty
            else:
                _count_elements(self, iterable)
        if kwds:
            self.update(kwds)
Esempio n. 10
0
def countby(seq, func=None, return_index=False):
    result = {}
    if func:
        if return_index:
            indexes = {}
            for value in seq:
                key = func(value)
                if key in result:
                    result[key] += 1
                else:
                    result[key] = 1
                    indexes[key] = value
            return result, indexes
        else:
            for value in seq:
                key = func(value)
                if key in result:
                    result[key] += 1
                else:
                    result[key] = 1
    else:
        _count_elements(result, seq)
    return result
Esempio n. 11
0
 def update_event(self, inp=-1):
     self.set_output_val(
         0, collections._count_elements(self.input(0), self.input(1)))
Esempio n. 12
0
import re
from collections import _count_elements

with open('holmes.txt') as f:
    the_text = f.read().lower()
    text_lst = re.findall('\w+', the_text)
    print(text_lst)
#sett = set()

dikt = _count_elements()
#for word in text_lst:
    #sett.add(word)

#sett = list(sett)
for item in text_lst:
    dikt.update
for x in range(0, len(sett)):
    dikt[sett[x]] = text_lst.count(sett[x])

print(dikt)

dikt2 = sorted(dikt.items(), key = itemgetter(1))[::-1]
print(dikt2)