コード例 #1
0
    def rewrite(self, s, p):
        """
        :type s: str
        :type p: str
        :rtype: List[int]

        looking for signature.
        use counter, which preserver multiple same char's signature.
        """
        from collections import Counter as CC

        pcc = CC(p)
        tmp_cc = CC()
        result = []


        for idx in range(len(s)):
            tmp_cc.update(s[idx])

            if idx >= len(p) - 1:
                if tmp_cc == pcc:
                    result.append(idx - (len(p) - 1))

                tmp_cc.subtract([s[idx - (len(p) - 1)]])
            # 長度不到持續累加

        return result
コード例 #2
0
ファイル: exponents.py プロジェクト: joewa/natu
    def update(self, *args, **kwargs):
        """D.update([E, ]**F) -> None.  Update D from dict/iterable E and F.
        If E present, does:  for k in E: D[k] = E[k]
        This is followed by: for k in F: D[k] = F[k]

        **Example:**

        >>> e = Exponents()
        >>> e.update(a=1)
        >>> e.update(dict(b=2), c=3)
        >>> e.update('1/d')
        >>> e # doctest: +SKIP
        Exponents({'a': 1, 'b': 2, 'c': 3, 'd': -1})

        .. testcleanup::
           >>> assert e == dict(a=1, b=2, c=3, d=-1)
        """
        try:
            # Assume args[0] is a string.
            arg = args[0].replace(' ', '')  # Remove spaces.
        except (IndexError, AttributeError):
            Counter.update(self, *args, **kwargs)
        else:
            if len(args) > 1:
                raise TypeError("update expected at most 1 arguments, got %i"
                                % len(args))
            Counter.update(self, Exponents.fromstr(arg), **kwargs)
コード例 #3
0
class WordsFrequency:
    def __init__(self, book: List[str]):
        from collections import Counter as CR
        self.cr = CR()
        self.cr.update(book)
        self.cr = dict(self.cr)

    def get(self, word: str) -> int:
        if word not in self.cr:
            return 0
        return self.cr[word]
コード例 #4
0
ファイル: exponents.py プロジェクト: endolith/natu
    def update(self, *args, **kwargs):
        """update([E, ]**F) -> None

        Update this :class:`Exponents` instance from :class:`dict`/iterable *E*
        and *F*.

        If *E* is present, this does:

           ``for k in E: D[k] = E[k]``

        Then it does:

           ``for k in F: D[k] = F[k]``

        Alternatively, *E* can be a string that is compatible with the
        :meth:`fromstr` constructor.

        **Example:**

        >>> e = Exponents()
        >>> e.update(a=1)
        >>> e.update(dict(b=2), c=3)
        >>> e.update('1/d')
        >>> e # doctest: +SKIP
        Exponents({'a': 1, 'b': 2, 'c': 3, 'd': -1})

        .. testcleanup::
           >>> assert e == dict(a=1, b=2, c=3, d=-1)
        """
        try:
            # Assume args[0] is a string.
            arg = args[0].replace(' ', '')  # Remove spaces.
        except (IndexError, AttributeError):
            Counter.update(self, *args, **kwargs)
        else:
            if len(args) > 1:
                raise TypeError("update expected at most 1 arguments, got %i"
                                % len(args))
            Counter.update(self, Exponents.fromstr(arg), **kwargs)
コード例 #5
0
            i += 1
            try:
                if newx < 0 or newy < 0:
                    raise IndexError
                if grid[newy][newx] != -1:
                    possibles.append(grid[newy][newx])
                    # print('Append ' + str(possibles[-1]))
            except IndexError:
                continue

    if len(possibles) == 1:
        newgrid[y][x] = possibles[0]
        for coord in [x, y]:
            if not (coord > 0 and coord < SIZE - 1):
                infinites.add(possibles[0])
        count.update([possibles[0]])
    # print(gridstring(newgrid))
    # else:
    #     print(x, y, possibles, i)
    # print(input())

# print(gridstring(newgrid))
# print(count)
for key in infinites:
    del count[key]

print(count.most_common(1)[0][1])

with open('grid.txt', 'w') as pg:
    pg.write(gridstring(newgrid))
コード例 #6
0
                existing[1].append(sleeptime)
                existing[2].append(awaketime)
                existing[0] += slept
                guards[currentGuard] = existing
            else:
                guards[currentGuard] = [slept, [sleeptime], [awaketime]]

    max = [0, [0, [], []]]
    for key, item in guards.items():
        # print(key, item)
        if item[0] > max[1][0]:
            max[0] = key
            max[1] = item

    # print(max)
    mins = Co()
    for sleep, awake in zip(max[1][1], max[1][2]):
        mins.update(range(sleep, awake))

    print(mins.most_common(1)[0][0] * max[0])

    maxMinGuard = [0, 0, 0]
    for guard, stats in guards.items():
        mins = Co()
        for sleep, awake in zip(stats[1], stats[2]):
            mins.update(range(sleep, awake))
        best = mins.most_common(1)[0]
        if best[1] > maxMinGuard[0]:
            maxMinGuard = [best[1], best[0], guard]

    print(maxMinGuard[2] * maxMinGuard[1])
コード例 #7
0
ファイル: counter.py プロジェクト: geniphi/findig
class _HitLog(AbstractLog):
    # This is a storage class that keep track of the hits that have
    # occurred over a given duration.
    # This particular implementation keeps track of hits in-memory.
    def __init__(self, duration, _): # last argument is resource (or None), but it is unused.
        self._hits = []
        self._delta = duration if isinstance(duration, timedelta) \
                               else timedelta(seconds=duration)
        self._thread_lock = Lock()
        self._counter = PyCounter()

    def _prune(self):
        if self._delta.total_seconds() < 0:
            # negative seconds means keep everything.
            return 

        now = datetime.now()
        with self._thread_lock:
            while self._hits and (now - self._hits[0][0]) > self._delta:
                time, pickled_counter_keys = heapq.heappop(self._hits)
                self._counter.subtract(pickle.loads(pickled_counter_keys))

    def _generate_counter_keys(self, partitions):
        sub_keys = chain.from_iterable(
            combinations(partitions, r) for r in range(1, len(partitions)+1)
        )

        for key_list in sub_keys:
            counter_key = tuple(sorted(map(lambda k: (k, partitions[k]), key_list)))
            yield counter_key

    def track(self, partitions):
        now = datetime.now()

        with self._thread_lock:
            counter_keys = tuple(self._generate_counter_keys(partitions))
            heapq.heappush(self._hits, (now, pickle.dumps(counter_keys)))
            self._counter.update(counter_keys)

    def count(self, **partitions):
        self._prune()

        if not partitions:
            return len(self._hits)

        else:
            counter_key = tuple(sorted(partitions.items()))
            return self._counter[counter_key]

    def __add__(self, other):
        if isinstance(other, _HitLog):
            if self._delta != other._delta:
                return NotImplemented
            else:
                new_log = _HitLog(self._delta, None)

                new_log._hits.extend(self._hits)
                new_log._hits.extend(other._hits)
                heapq.heapify(new_log._hits)

                new_log._counter.update(self._counter)
                new_log._counter.update(other._counter)
                
                return new_log

        else:
            return NotImplemented

    def __iter__(self):
        ascending = heapq.nsmallest(self.count(), self._hits)
        for time, partitions in ascending:
            yield Hit(time, partitions)

    def __len__(self):
        return self.count()

    def __repr__(self):
        return "HitLog({})".format(self.count())
コード例 #8
0
ファイル: dimensions.py プロジェクト: speezepearson/units
 def update(self, *args, **kwargs):
     Counter.update(self, *args, **kwargs)
     self.clean()