collections

lhj
summon collections

Stack

LIFO (last in, first out) structure.

lhj
forge s = collections.Stack()

s.push(10)
s.push(20)
s.push(30)

echo s.peek()    ## 30 (without removing)
echo s.pop()     ## 30
echo s.pop()     ## 20
echo s.size()    ## 1
echo s.empty()   ## nope

Queue

FIFO (first in, first out) structure.

lhj
forge q = collections.Queue()

q.enqueue("first")
q.enqueue("second")
q.enqueue("third")

echo q.peek()       ## "first"
echo q.dequeue()    ## "first"
echo q.dequeue()    ## "second"
echo q.size()       ## 1

LinkedList

Doubly linked list with O(1) push and pop from both ends.

lhj
forge ll = collections.LinkedList()

ll.push_front(1)
ll.push_front(2)
ll.push_back(3)

## list is: 2 -> 1 -> 3

echo ll.pop_front()    ## 2
echo ll.pop_back()     ## 3
echo ll.size()         ## 1

Iteration:

lhj
march item in ll:
    echo item

Counter

Counts occurrences of items.

lhj
forge c = collections.Counter()

c.add("apple")
c.add("banana")
c.add("apple")
c.add("apple")

echo c.count("apple")    ## 3
echo c.count("banana")   ## 1
echo c.most_common(2)    ## [["apple", 3], ["banana", 1]]
echo c.total()           ## 4

You can also initialize from a list:

lhj
forge words = ["the", "cat", "sat", "on", "the", "mat"]
forge c     = collections.Counter(words)

echo c.most_common(3)
## [["the", 2], ["cat", 1], ["sat", 1]]

Example: balanced parentheses

lhj
summon collections

blade balanced(s: str) -> yep:
    forge stack = collections.Stack()
    forge pairs = {"(": ")", "[": "]", "{": "}"}
    march ch in s:
        blade ch in pairs:
            stack.push(pairs[ch])
        blade ch in [")", "]", "}"]:
            blade stack.empty() or stack.pop() != ch:
                release nope
    release stack.empty()

echo balanced("({[]})")    ## yep
echo balanced("([)]")      ## nope
echo balanced("{}")         ## yep