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?