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__(inout self: Self)
Create a new, empty Counter object.
__init__(inout self: 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__(inout self: Self, *, other: Self)
Create a new Counter by copying another Counter.
Args:
- other (
Self
): The Counter to copy.
__bool__
__bool__(self: Self) -> Bool
Check if the Counter is empty or not.
Returns:
False
if the Counter is empty, True
otherwise.
__getitem__
__getitem__(self: 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: 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) -> 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) -> Self
Return a shallow copy of the Counter, stripping non-positive counts.
Returns:
A shallow copy of the Counter.
__lt__
__lt__(self: 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: 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: 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: 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: 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: 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: 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: 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: 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: 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: 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: 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: 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: Self, other: Self)
Intersection: keep common elements with the minimum count.
Args:
- other (
Self
): The other Counter to intersect with.
__ior__
__ior__(inout self: 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: Self) -> _DictKeyIter[0, V, Int, *[0,0]._data, 1]
Iterate over the keyword dict's keys as immutable references.
Returns:
An iterator of immutable references to the Counter values.
__len__
__len__(self: Self) -> Int
Returns the number of elements currently stored in the Counter.
Returns:
The number of elements in the Counter.
get
get(self: 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: 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: 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: 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_is_lifetime] self: Self) -> _DictKeyIter[$0, V, Int, $1._data, 1]
Iterate over the Counter's keys as immutable references.
Returns:
An iterator of immutable references to the Counter keys.
values
values(ref [self_is_lifetime] self: Self) -> _DictValueIter[$0, V, Int, $1._data, 1]
Iterate over the Counter's values as references.
Returns:
An iterator of references to the Counter values.
items
items(self: Self) -> _DictEntryIter[0, V, Int, *[0,0]._data, 1]
Iterate over the dict's entries as immutable references.
Returns:
An iterator of immutable references to the Counter entries.
clear
clear(inout self: Self)
Remove all elements from the Counter.
popitem
popitem(inout self: 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: 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: Self, n: Int) -> List[CountTuple[V], 0]
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: Self) -> List[V, 0]
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: 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: 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!
😔 What went wrong?