Mojo struct
Counter
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 the dictionary as keys.
Usage:
from collections import Counter
var c = Counter[String](List("a", "a", "a", "b", "b", "c", "d", "c", "c"))
print(c["a"]) # prints 3
print(c["b"]) # prints 2
from collections import Counter
var c = Counter[String](List("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.
Implemented traits
AnyType
,
Boolable
,
CollectionElement
,
Copyable
,
Movable
,
Sized
Methods
__init__
__init__(out self)
Create a new, empty Counter object.
__init__(out self, items: List[V, hint_trivial_type])
Create a from an input iterable.
Args:
- items (
List[V, hint_trivial_type]
): A list of items to count.
__init__(out self, *, other: Self)
Create a new Counter by copying another Counter.
Args:
- other (
Self
): The Counter to copy.
__bool__
__bool__(self) -> Bool
Check if the Counter is empty or not.
Returns:
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:
The count of the key.
__setitem__
__setitem__(inout 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
Substract from an empty Counter. Strips positive and zero counts, and flips the sign on negative counts.
Returns:
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:
A shallow copy of the Counter.
__lt__
__lt__(self, other: Self) -> Bool
Check if all counts are less than in the other Counter.
Args:
- other (
Self
): The other Counter to compare to.
Returns:
True if all counts are less than in the other Counter, False otherwise.
__le__
__le__(self, other: Self) -> Bool
Check if all counts are less than or equal to the other Counter.
Args:
- other (
Self
): The other Counter to compare to.
Returns:
True if all counts are less than or equal to the other Counter, False otherwise.
__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:
True if the two Counters are equal, False otherwise.
__ne__
__ne__(self, other: Self) -> Bool
Check if all counts disagree. Missing counts are treated as zero.
Args:
- other (
Self
): The other Counter to compare to.
Returns:
True if the two Counters are not equal, False otherwise.
__gt__
__gt__(self, other: Self) -> Bool
Check if all counts are greater than in the other Counter.
Args:
- other (
Self
): The other Counter to compare to.
Returns:
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 the other Counter.
Args:
- other (
Self
): The other Counter to compare to.
Returns:
True if all counts are greater than or equal to the other Counter, False otherwise.
__contains__
__contains__(self, key: V) -> Bool
Check if a given key is in the dictionary or not.
Args:
- key (
V
): The key to check.
Returns:
True if there key exists in the dictionary, 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:
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:
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:
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:
A new Counter with all elements and the maximum count of the two Counters.
__iadd__
__iadd__(inout self, other: Self)
Add counts from another Counter to this Counter.
Args:
- other (
Self
): The other Counter to add to this Counter.
__isub__
__isub__(inout self, other: Self)
Subtract counts from another Counter from this Counter.
Args:
- other (
Self
): The other Counter to subtract from this Counter.
__iand__
__iand__(inout self, other: Self)
Intersection: keep common elements with the minimum count.
Args:
- other (
Self
): The other Counter to intersect with.
__ior__
__ior__(inout 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, hint_trivial_type], value: Int) -> Self
Create a new Counter from a list of keys and a default value.
Args:
- keys (
List[V, hint_trivial_type]
): The keys to create the Counter from. - value (
Int
): The default value to associate with each key.
Returns:
A new Counter with the keys and default value.
__iter__
__iter__(self) -> _DictKeyIter[V, Int, *[0,0]._data]
Iterate over the keyword dict's keys as immutable references.
Returns:
An iterator of immutable references to the Counter values.
__len__
__len__(self) -> Int
Returns the number of elements currently stored in the Counter.
Returns:
The number of elements in the Counter.
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:
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:
A copy of the value if it was present, otherwise default.
pop
pop(inout self, value: V) -> Int
Remove a value from the Counter by value.
Args:
- value (
V
): The value to remove from the Counter.
Returns:
The value associated with the key, if it was in the Counter.
Raises:
"KeyError" if the key was not present in the Counter.
pop(inout self, value: V, owned 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:
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, $1._data]
Iterate over the Counter's keys as immutable references.
Returns:
An iterator of immutable references to the Counter keys.
values
values(ref self) -> _DictValueIter[V, Int, $1._data]
Iterate over the Counter's values as references.
Returns:
An iterator of references to the Counter values.
items
items(self) -> _DictEntryIter[V, Int, *[0,0]._data]
Iterate over the dict's entries as immutable references.
Returns:
An iterator of immutable references to the Counter entries.
clear
clear(inout self)
Remove all elements from the Counter.
popitem
popitem(inout self) -> CountTuple[V]
Remove and return an arbitrary (key, value) pair from the Counter.
Returns:
A CountTuple containing the key and value of the removed item.
Raises:
"KeyError" if the Counter is empty.
total
total(self) -> Int
Return the total of all counts in the Counter.
Returns:
The total of all counts in the Counter.
most_common
most_common(self, n: Int) -> List[CountTuple[V]]
Return a list of the n
most common elements and their counts from the most common to the least.
Args:
- n (
Int
): The number of most common elements to return.
Returns:
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:
An iterator over the elements in the Counter.
update
update(inout 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(inout self, other: Self)
Subtract count. Both inputs and outputs may be zero or negative.
Args:
- other (
Self
): The Counter to subtract from this Counter.
Was this page helpful?
Thank you! We'll create more content like this.
Thank you for helping us improve!