Skip to main content

Mojo struct

Counter

struct Counter[V: KeyElement, H: Hasher = default_hasher]

A container for counting hashable items.

The value type must be specified statically, unlike a Python Counter, which can accept arbitrary value types.

The value type must implement the KeyElement trait, as its values are stored in a dictionary as keys.

Usage:

from collections import Counter
var c = Counter[String]("a", "a", "a", "b", "b", "c", "d", "c", "c")
print(c["a"]) # prints 3
print(c["b"]) # prints 2

Parameters

  • V (KeyElement): The value type to be counted. Currently must be KeyElement.
  • H (Hasher): The type of the hasher in the underlying dictionary.

Implemented traits

AnyType, Boolable, Copyable, Defaultable, Equatable, Iterable, Movable, Sized, UnknownDestructibility

Aliases

__copyinit__is_trivial

comptime __copyinit__is_trivial = False

__del__is_trivial

comptime __del__is_trivial = False

__moveinit__is_trivial

comptime __moveinit__is_trivial = True

IteratorType

comptime IteratorType[iterable_mut: Bool, //, iterable_origin: Origin[iterable_mut]] = _DictKeyIter[V, Int, H, iterable_origin]

Parameters

  • iterable_mut (Bool):
  • iterable_origin (Origin):

Methods

__init__

__init__(out self)

Create a new, empty Counter object.

__init__(out self, var *values: V)

Create a new Counter from a list of values.

Usage:

from collections import Counter
var c = Counter[String]("a", "a", "a", "b", "b", "c", "d", "c", "c")
print(c["a"])  # print 3
print(c["b"])  # print 2

Args:

  • *values (V): A list of values to count.

__init__(out self, items: List[V])

Create a Counter from an input iterable.

Usage:

from collections import Counter
var c = Counter[String](["a", "a", "a", "b", "b", "c", "d", "c", "c"])
print(c["a"]) # prints 3
print(c["b"]) # prints 2

Args:

  • items (List): A list of items to count.

__bool__

__bool__(self) -> Bool

Check if the Counter is empty or not.

Returns:

Bool: False if the Counter is empty, True otherwise.

__getitem__

__getitem__(self, key: V) -> Int

Get the count of a key.

Args:

  • key (V): The key to get the count of.

Returns:

Int: The count of the key.

__setitem__

__setitem__(mut self, value: V, count: Int)

Set a value in the keyword Counter by key.

Args:

  • value (V): The value to associate with the specified count.
  • count (Int): The count to store in the Counter.

__neg__

__neg__(self) -> Self

Subtract from an empty Counter. Strips positive and zero counts, and flips the sign on negative counts.

Returns:

Self: A new Counter with stripped counts and negative counts.

__pos__

__pos__(self) -> Self

Return a shallow copy of the Counter, stripping non-positive counts.

Returns:

Self: A shallow copy of the Counter.

__eq__

__eq__(self, other: Self) -> Bool

Check if all counts agree. Missing counts are treated as zero.

Args:

  • other (Self): The other Counter to compare to.

Returns:

Bool: True if the two Counters are equal, False otherwise.

__contains__

__contains__(self, key: V) -> Bool

Check if a given key is in the Counter or not.

Args:

  • key (V): The key to check.

Returns:

Bool: True if there key exists in the Counter, False otherwise.

__add__

__add__(self, other: Self) -> Self

Add counts from two Counters.

Args:

  • other (Self): The other Counter to add to this Counter.

Returns:

Self: A new Counter with the counts from both Counters added together.

__sub__

__sub__(self, other: Self) -> Self

Subtract counts, but keep only results with positive counts.

Args:

  • other (Self): The other Counter to subtract from this Counter.

Returns:

Self: A new Counter with the counts from the other Counter subtracted from this Counter.

__and__

__and__(self, other: Self) -> Self

Intersection: keep common elements with the minimum count.

Args:

  • other (Self): The other Counter to intersect with.

Returns:

Self: A new Counter with the common elements and the minimum count of the two Counters.

__or__

__or__(self, other: Self) -> Self

Union: keep all elements with the maximum count.

Args:

  • other (Self): The other Counter to union with.

Returns:

Self: A new Counter with all elements and the maximum count of the two Counters.

__iadd__

__iadd__(mut self, other: Self)

Add counts from another Counter to this Counter.

Args:

  • other (Self): The other Counter to add to this Counter.

__isub__

__isub__(mut self, other: Self)

Subtract counts from another Counter from this Counter, but kee only results with positive counts.

Args:

  • other (Self): The other Counter to subtract from this Counter.

__iand__

__iand__(mut self, other: Self)

Intersection: keep common elements with the minimum count.

Args:

  • other (Self): The other Counter to intersect with.

__ior__

__ior__(mut self, other: Self)

Union: keep all elements with the maximum count.

Args:

  • other (Self): The other Counter to union with.

fromkeys

static fromkeys(keys: List[V], value: Int) -> Self

Create a new Counter from a list of keys and a default value.

Args:

  • keys (List): The keys to create the Counter from.
  • value (Int): The default value to associate with each key.

Returns:

Self: A new Counter with the keys and default value.

__iter__

__iter__(ref self) -> _DictKeyIter[V, Int, H, self_is_origin]

Iterate over the Counter's keys as immutable references.

Returns:

_DictKeyIter: An iterator of immutable references to the Counter values.

__len__

__len__(self) -> Int

Returns the number of elements currently stored in the Counter.

Returns:

Int: The number of elements in the Counter.

le

le(self, other: Self) -> Bool

Check if all counts are less than or equal to those in the other Counter.

Note that since we check that all counts satisfy the condition, this comparison does not make Counters totally ordered.

Args:

  • other (Self): The other Counter to compare to.

Returns:

Bool: True if all counts are less than or equal to the other Counter, False otherwise.

lt

lt(self, other: Self) -> Bool

Check if all counts are less than those in the other Counter.

Note that since we check that all counts satisfy the condition, this comparison does not make Counters totally ordered.

Args:

  • other (Self): The other Counter to compare to.

Returns:

Bool: True if all counts are less than in the other Counter, False otherwise.

gt

gt(self, other: Self) -> Bool

Check if all counts are greater than those in the other Counter.

Note that since we check that all counts satisfy the condition, this comparison does not make Counters totally ordered.

Args:

  • other (Self): The other Counter to compare to.

Returns:

Bool: True if all counts are greater than in the other Counter, False otherwise.

ge

ge(self, other: Self) -> Bool

Check if all counts are greater than or equal to those in the other Counter.

Note that since we check that all counts satisfy the condition, this comparison does not make Counters totally ordered.

Args:

  • other (Self): The other Counter to compare to.

Returns:

Bool: True if all counts are greater than or equal to the other Counter, False otherwise.

get

get(self, value: V) -> Optional[Int]

Get a value from the Counter.

Args:

  • value (V): The value to search for in the Counter.

Returns:

Optional: An optional value containing a copy of the value if it was present, otherwise an empty Optional.

get(self, value: V, default: Int) -> Int

Get a value from the Counter.

Args:

  • value (V): The value to search for in the Counter.
  • default (Int): Default count to return.

Returns:

Int: A copy of the value if it was present, otherwise default.

pop

pop(mut self, value: V) -> Int

Remove a value from the Counter by value.

Args:

  • value (V): The value to remove from the Counter.

Returns:

Int: The value associated with the key, if it was in the Counter.

Raises:

"KeyError" if the key was not present in the Counter.

pop(mut self, value: V, var default: Int) -> Int

Remove a value from the Counter by value.

Args:

  • value (V): The value to remove from the Counter.
  • default (Int): Optionally provide a default value to return if the value was not found instead of raising.

Returns:

Int: The value associated with the key, if it was in the Counter. If it wasn't, return the provided default value instead.

Raises:

"KeyError" if the key was not present in the Counter and no default value was provided.

keys

keys(ref self) -> _DictKeyIter[V, Int, H, origin_of(self_is_origin._data)]

Iterate over the Counter's keys as immutable references.

Returns:

_DictKeyIter: An iterator of immutable references to the Counter keys.

values

values(ref self) -> _DictValueIter[V, Int, H, origin_of(self_is_origin._data)]

Iterate over the Counter's values as references.

Returns:

_DictValueIter: An iterator of references to the Counter values.

items

items(self) -> _DictEntryIter[V, Int, H, origin_of(self._data)]

Iterate over the Counter's entries as immutable references.

Returns:

_DictEntryIter: An iterator of immutable references to the Counter entries.

clear

clear(mut self)

Remove all elements from the Counter.

popitem

popitem(mut self) -> CountTuple[V]

Remove and return an arbitrary (key, value) pair from the Counter.

Returns:

CountTuple: A CountTuple containing the key and value of the removed item.

Raises:

"KeyError" if the Counter is empty.

total

total(self) -> UInt

Return the total of all counts in the Counter.

Returns:

UInt: The total of all counts in the Counter.

most_common

most_common(self, n: UInt) -> List[CountTuple[V]]

Return a list of the n most common elements and their counts from the most common to the least.

Args:

  • n (UInt): The number of most common elements to return.

Returns:

List: A list of the n most common elements and their counts.

elements

elements(self) -> List[V]

Return an iterator over elements repeating each as many times as its count.

Returns:

List: An iterator over the elements in the Counter.

update

update(mut self, other: Self)

Update the Counter, like Dict.update() but add counts instead of replacing them.

Args:

  • other (Self): The Counter to update this Counter with.

subtract

subtract(mut self, other: Self)

Subtract counts. Both inputs and outputs may be zero or negative.

Args:

  • other (Self): The Counter to subtract from this Counter.

Was this page helpful?