- Ling 3.0 Tiny is a free model from inclusionai that you can run on your own computer. In our tests it's not one we'd recommend right now: 58 out of 100, #34 of 72.
- It solved 14 of 30 coding jobs and scored 70 on reading documents. On our hardest tasks it scored 24.
- Runs on an 8 GB graphics card or a Mac with 16 GB.
Coding
Our coding test is 30 programming jobs, from small ones like reading time durations or cleaning up messy data to harder ones like a config-file parser or a double-entry ledger. We run each answer against tests the model never sees, and a job only counts if everything passes. Ling 3.0 Tiny got 14 of 30 right. The best local coders solved 29 of 30.
Reading documents
The second test hands the model things like an expense claim thread, a pay stub or an insurance statement, and asks for specific numbers and dates. Many questions need a bit of math, or noticing a correction further down the email. Ling 3.0 Tiny scored 70; the best model scored 100.
| Test | Score | Public questions | Secret questions |
|---|---|---|---|
| Coding | 47 | 57 | 44 |
| Reading documents | 70 | 100 | 62 |
| Decisions | 73 | 82 | 70 |
On the 18 hardest tasks (included in the scores above) it scored 24. This number separates the top models.
This model did much better on our public questions than on the secret ones. Sometimes that's luck; it can also mean the model has seen the public questions before.
We tested the full-size version online. The smaller versions you download usually score a little lower.
Can your computer run it?
You can download Ling 3.0 Tiny in several sizes. Smaller versions fit on more computers and lose a little quality, so pick the biggest one that fits.
| Your computer | Runs it? | Version to download |
|---|---|---|
| Graphics card, 8 GB | Yes | Q5 |
| Graphics card, 12 GB | Yes | Q8 |
| Graphics card, 16 GB | Yes | Q8 |
| Graphics card, 24 GB | Yes | Q8 |
| Graphics card, 32 GB | Yes | Q8 |
| Mac, 16 GB | Yes | Q8 |
| Mac, 24 GB | Yes | Q8 |
| Mac, 32 GB | Yes | Q8 |
| Mac, 48 GB | Yes | Q8 |
| Mac, 64 GB | Yes | Q8 |
| Mac, 96 GB | Yes | Q8 |
| Mac, 128 GB | Yes | Q8 |
For normal-length chats. Long documents need more memory. Q4 or Q8? · How we worked this out
How to try it
Search for "Ling 3.0 Tiny GGUF" in LM Studio or on Hugging Face and pick the version that fits your computer. New to this? Start with our Ollama guide.
Want the strongest all-rounder instead? Qwen3.6 27B scored 97.
Its actual answers
What Ling 3.0 Tiny wrote for our public questions, word for word.
Coding: INI parser (hard) Didn't work
We need to write parse_ini function that parses an INI string following specific rules. Let's break down requirements:
1. Section headers: [name] with whitespace around name. Case-sensitive.
2. Inside a section: key = value or key: value. Split on first = or :. Keys stripped and lowercased; values stripped (but we need to handle quoted values carefully).
3. Empty lines or lines starting with ; or # are ignored.
4. Inline comment starts at ; or # (whitespace followed by ; or #) and runs to end of line, unless inside double-quoted value.
5. Double-quoted value keeps everything inside quotes exactly (no stripping, comment characters allowed); quotes removed.
6. Continuation lines: line that starts with whitespace and follows a key line is continuation; its stripped text is appended to previous value with a "\n" between them.
7. If same key appears twice in a section, later value wins.
8. DEFAULT section is special: not returned as a section, but its keys are inherited by every other section unless that section defines the key itself.
9. Interpolation: ${key} and ${section:key} references. Recursive. Missing key or section raises KeyError. Reference cycle raises ValueError.
10. A key line before any section header, or a malformed line, raises ValueError.
We need to implement this in Python 3.12, standard library only. Return type: dict[str, dict[str, str]].
We need to handle:
- Parsing of INI string.
- Section handling.
- Key-value parsing with first = or : as separator.
- Quoted values.
- Comments inside lines (but not in quoted values).
- Continuation lines.
- DEFAULT inheritance.
- Interpolation.
- Error handling (ValueError, KeyError, ValueError for cycles).
Let's design the parser step by step.
First, we need to split the text into lines, and process each line. We need to handle continuation lines. A continuation line is one that starts with whitespace and follows a key line. But how do we know what is a "key line"? A line that is not a section header, not a comment, not empty, and not a continuation line. Actually, continuation lines are those that are indented. But what about lines that start with whitespace but are not continuation? The rule says: "A line that starts with whitespace and follows a key line is a continuation". This implies we need to know if the previous line was a key line (i.e., a non-section, non-comment, non-empty line that had a key). So we can track a state: current section, current key, current value. When we see a line that starts with whitespace and current section is set and we have a current key (or maybe any line), it's continuation. But if we see a line that starts with whitespace but current section is not set (i.e., we are in default or before any section), then is it continuation? The rule says "follows a key line". So only after a key line.
Also, we need to handle the case where a line is malformed (e.g., a line that has a key but no value, or something). But let's see the exact requirements.
The rules mention: "A key line before any section header, or a malformed line, raises ValueError."
So if we see a line that looks like a key (i.e., has something before = or :) but no section, it's a malformed line.
Let's outline the algorithm:
- Initialize `sections = {}` (dict of dict of str -> str).
- Initialize `current_section = None`.
- We'll process lines one by one.
- For each line:
- Strip leading whitespace (or just check if it starts with whitespace).
- If the stripped line is empty, skip.
- If the first non-space character is `;` or `#`, skip (inline comment rule: whitespace then ; or #). But note: an inline comment starts at `;` or `#` with whitespace before it. So if line starts with `;` or `#`, it's a comment line (entire line is comment). If it has whitespace then `;` or `#`, it's an inline comment on the rest of the line.
- If the line starts with `[`, it's a section header. Parse `[name]` where name is stripped, case-sensitive. Set current_section = name. Continue.
- If the line starts with whitespace and current_section is not None and we have a current key (from previous line), it's a continuation line. We need to append to the current value with a newline.
- Otherwise, it's a key-value line (or malformed). Parse key and value.
But we need to be careful: a line could be a comment line if it starts with `;` or `#` (after stripping whitespace). But what if it has whitespace and then comment? That's an inline comment. The rule says: "A line that is empty or whose first non-space character is `;` or `#` is ignored." So lines that start with whitespace then `;` or `#` are ignored. This is handled by: if after stripping leading whitespace, the first char is `;` or `#`, skip the whole line.
But what about a line that is a key-value but has a comment after it? The comment is inline. We need to process comments after splitting the value.
For key-value lines: we need to split on the first `=` or `:`. But we also need to handle quotes. So algorithm for a line that is not a section header, not a comment, not empty:
1. Find the first occurrence of `=` or `:` that is not inside a double-quoted string.
- We need to scan the line, handling quoted strings.
2. Split into key and value.
- Key is stripped and lowercased.
- Value is the rest of the string.
3. Then process the value:
- If the value starts with a double quote, it's a quoted value: we take everything up to the closing double quote (not including the quotes). But we need to be careful about escaped quotes? The rules don't mention escaping. In many INI dialects, escaped quotes are not allowed or are just part of the value. The rule says: "A value wrapped in double quotes keeps everything inside the quotes exactly (no stripping, comment characters allowed); the quotes are removed." It doesn't mention escaping. So we treat `"` as start and end of quoted value. We need to find the first `"` after the key/value split, and then the next `"` after that is the closing quote. But if there are multiple quotes, we need to be careful. The rule says "keeps everything inside the quotes exactly (no stripping, comment characters allowed); the quotes are removed." This implies we just find the first matching pair? Actually, typical INI parsers treat the value as quoted if it starts with `"`, and then everything up to the next `"` is the value, and quotes are removed. But what if there's a `"` inside the value? The rule doesn't mention escaping. So we should assume simple unescaped double quotes. We need to find the next `"` after the first one, and that's the end. If the value starts with `"` and there's no matching end `"` before the end of line, it's an error? The spec doesn't specify. Let's assume the value is a quoted string and the end of line is the end of the value (unless there's a comment after the closing quote). But inline comments can appear after the quoted value? The comment rule says: "A line that starts with whitespace and follows a key line is a continuation..." and "A line that starts with whitespace and follows a key line is a continuation: its stripped text is appended to the previous value with a "\n" between them." So if there is an inline comment after a quoted value, the comment is ignored. But wait, inline comments are processed after value parsing. If the value is quoted and there's a comment after it, the comment would be a separate line? No, inline comment is on the same line. So for a quoted value, the comment character is not allowed inside the quotes. So we need to parse inline comments first, then the value.
Actually, let's think about the parsing order:
1. We have a line.
2. We need to check if it's a continuation line.
3. If not, and not a comment line, and not a section header, we need to parse it as key-value.
4. To parse key-value, we first need to handle inline comments. But inline comments can be after the value part. But if the value is quoted, comments can't appear inside. So we need to process comments on the line, but we need to know where the value ends.
Let's propose a line parsing approach:
For a non-empty, non-comment line (i.e., the line is not a comment and not empty, and doesn't start with `;` or `#` after stripping):
- We need to extract the value. The value can be quoted or unquoted.
- In the value, the last part of the line after the key: after the `=` or `:` split, the rest of the string is the value.
- If the value starts with `"`, then we need to find the closing `"` and strip it. Everything before the first `"` is the key? No, the key is before the `=` or `:`. The value is after the first `=` or `:`. So after splitting, we get key and value string. Then we check if value starts with `"`. If yes, we look for the next `"` to close the string. We include everything between the quotes (including any internal quotes? The rule says "keeps everything inside the quotes exactly (no stripping, comment characters allowed); the quotes are removed." So internal quotes are not special; we just find the first matching closing quote. If the closing quote is inside the string, it would end the value. But the spec doesn't mention escaping. So we assume unescaped double quotes.
- If the value does not start with `"`, then it's a simple string. Then we need to check for inline comments. Inline comment starts at whitespace followed by `;` or `#`. So we need to find the first occurrence of `;` or `#` that is preceded by whitespace (or is at the start of the line). But the line is the value part. We need to strip the comment and its preceding whitespace.
Wait, the rules say: "A line that is empty or whose first non-space character is `;` or `#` is ignored." This is for entire lines. For inline comments, it says: "A inline comment starts at ` ;` or ` #` (whitespace followed by `;` or `#`) and runs to the end of the line, unless it is inside a double-quoted value."
So for a line that is a key-value, we have a value that might contain a comment. But the comment can be inside the value only if the value is not quoted. Actually, the rule says: "unless it is inside a double-quoted value". So if the value is a quoted string, the entire value is inside quotes, and comments inside it are ignored? Or does it mean that comments are ignored only if they appear after the quoted value, not inside? The wording "unless it is inside a double-quoted value" means that inline comments are ignored if they occur inside a double-quoted value (i.e., the value is quoted). So if the value is quoted, we should not parse comments inside the value.
So the algorithm for extracting value:
1. Split the line on the first `=` or `:` that is not inside quotes (if quoted, we don't want to split on `=` inside quotes). Wait, but the split is on the first `=` or `:` in the value part? Actually, we need to split on the first `=` or `:` that is not inside a quoted string. So if we have a key and value separated by `=`, and the value is quoted, the first `=` after the key is the separator. The quotes are part of the value. So we must first find the separator, handling quotes.
Let's define the value part. We can scan the line character by character to find the first `=` or `:` that is not inside a double-quoted string.
But what about a line like `key = "value with = inside"`? The first `=` is the separator. The value is `"value with = inside"`. After removing quotes, the value is `value with = inside`.
If we have `key = value with # comment`, then the value is `value with # comment`, and the `#` is a comment? Actually, if it's not quoted, `# comment` is an inline comment. But the rule says: "A line that starts with whitespace and follows a key line is a continuation: its stripped text is appended to the previous value with a "\n" between them." That is for continuation lines. For inline comments, the rule says they are ignored (except inside quoted values).
So parsing inline comments: we scan the line (the value part) for a comment. A comment starts at whitespace followed by `;` or `#`. The comment runs to the end of the line, but inside double quotes it's ignored.
But the inline comment can appear at any position in the line. So after extracting the value (including the quoted part), we need to strip any comment that is not inside quotes. If the value is quoted, the entire value (including any interior quotes) is kept, and we don't process comments inside.
But there is a subtlety: what if the value is a quoted string and the line also has an inline comment after the closing quote? For example: `key = "value" ; comment`. In this case, the `;` is after the closing quote, and the comment is a comment. The rule says "unless it is inside a double-quoted value". So the comment is not inside the double-quoted value. It is outside. So we need to strip the comment.
So the process for a key-value line:
- Split into key and value by finding the first `=` or `:` that is not inside a double-quoted value. Actually, if the value is not quoted, we can just split on the first `=` or `:`. If it is quoted, we need to find the first `=` or `:` that is not inside quotes.
- So we can find the first `=` or `:` that is not inside quotes. We iterate character by character, tracking if we are inside a double-quoted string.
- But we also need to ensure that the line has a key before the `=` or `:`. The key is the part before the first `=` or `:` that is not inside quotes.
Wait, if the value is quoted, the first `=` or `:` after the key is the separator. But what if the line is `key = "value with : inside"`? The first `:` is inside the quotes, so we need to find the first unquoted `:` or `=`. But if we have a key `key` and value `"value with : inside"`, the separator is `=`, and the value is the quoted string. If the line is `key: "value"`, separator is `:`. If the line is `key: "value" : "nested"`, the first unquoted `:` is the separator? Actually, the line `key: "value" : "nested"` has two colons: the first one is the separator, the second is inside the quoted string. So we only split on the first unquoted `:` or `=`.
But what if the value is quoted and there is no unquoted separator? Then we just have a value.
What about a line like `key = value = "with = inside"`? The first `=` is the separator, value is `"value = "with = inside"`. But this is not valid because the quoted value includes `=`. The separator is the first `=`. The value is then `"value = "with = inside"` which includes the closing quote? Wait, after the first `=`, the value starts. If the value is quoted, we need to find the first `"` after the key and then the next `"` to close. If there is an `=` inside the quoted string, we just keep it. So the first `=` after the key is the separator, even if it appears inside the quoted value? But if the value is quoted, it starts with `"`, and the separator is the first `=` or `:`. We find the first `=` or `:` that is not inside a double-quoted string. In `key = "value = inner"`, the first `=` after the key is the one that separates `key` and `"value = inner"`. So we find the first unquoted `=`. That's fine.
But what about `key: value = "with colon"`? The first unquoted `:` is the separator. That's fine.
What about a line like `key : = value`? That's invalid? The spec says split on first `=` or `:`. It doesn't say anything about nested quotes. So we just take the first unquoted `=` or `:`.
Now, after splitting, the key is stripped and lowercased. The value is the rest of the string.
Now, for the value, we need to check if it starts with a double quote. If so, find the closing quote. The value is the string between the quotes (including any quotes inside? The rule says "keeps everything inside the quotes exactly (no stripping, comment characters allowed); the quotes are removed." So we keep the content inside the quotes, including any internal quotes or `#` or `;` characters. We remove the outer quotes.
But what if there's no closing quote? For example, `key = "value`. Then the value is the string from after the `=` to the end of line (if no closing quote). The rule doesn't specify. We probably should assume the quoted value ends at the next unescaped quote. If there's no closing quote, the value is just the text until the end of line. But the comment rule says "unless it is inside a double-quoted value". So if we have an unclosed quote, the value includes the rest of the line? The spec doesn't mention an error for unclosed quotes. So we can just take everything from the opening quote to the end of line, strip the quotes? Actually, the spec says "A value wrapped in double quotes keeps everything inside the quotes exactly (no stripping, comment characters allowed); the quotes are removed." This implies that if the value is wrapped in double quotes, we keep the content inside. If there is no closing quote, the value is just the text from the opening quote to the end. But then the quotes are removed? That would be weird. I think we should assume the quoted value is properly closed. But for robustness, we can handle the case where there is a closing quote somewhere. If there is no closing quote, we could treat it as an unquoted value (including the opening quote as part of the value). But the spec says "A value wrapped in double quotes keeps everything inside the quotes exactly (no stripping, comment characters allowed); the quotes are removed." This is a definition of the behavior. If the value is not properly closed, it's not a value wrapped in double quotes? But the rule says "A line that starts with whitespace and follows a key line is a continuation". That is for continuation.
Let's think about the inline comment handling. After extracting the value, we need to strip any inline comments. But if the value is quoted, we don't strip comments inside. So we need to handle the comment stripping after we know if the value is quoted.
So for a non-quoted value:
- Find the first occurrence of `;` or `#` preceded by whitespace (or at the start of the string? The rule says "A line that starts with whitespace and follows a key line is a continuation". That's different. For inline comments, it says "A inline comment starts at ` ;` or ` #` (whitespace followed by `;` or `#`) and runs to the end of the line". So comment starts at whitespace followed by `;` or `#`. This means if a value contains `;` or `#` without preceding whitespace, it's not a comment. But if the value is unquoted and contains a `#`, the `#` is a comment. Actually, the rule says "unless it is inside a double-quoted value". So for unquoted values, we process comments.
But wait: if we have an unquoted value that is `value#comment`, the `#` is the comment character? Yes, because it's not preceded by whitespace? The rule says "whitespace followed by `;` or `#`". So if it's at the beginning of the value (no preceding whitespace), then `#` is not preceded by whitespace, so it's not a comment. It's part of the value. But then the value is `value#comment` with no comment. So we need to be careful.
So for unquoted values, we need to find the first `;` or `#` that is preceded by whitespace (or start of string? No, the rule explicitly says whitespace followed by `;` or `#`. So the `#` or `;` must have a whitespace character immediately before it. If the value is at the start of the line, it's not a comment.
But what if the value is `key = "value#comment"`? The value is quoted, so comment is ignored.
How to implement this efficiently:
Let's define a function that parses a line (after stripping a comment or something) into key-value.
We can split the line into two parts: before the comment (if any) and the comment. But the comment is attached to the value part.
Better:
Given a line (the raw line string after stripping leading/trailing whitespace? No, we need to know if it's a continuation. The continuation detection is: line starts with whitespace and we have a current key. So we need to keep track of the raw line.
Let's define the processing loop:
```
lines = tex Coding: TTL LRU (hard) Didn't work
We need to implement a TTLCache (Time-To-Live cache) that is also LRU. It has capacity, ttl (float), and clock (a callable that returns current time in seconds). The cache should be LRU with TTL. The entries expire based on current time. When putting a new key, if capacity is exceeded, first remove all expired entries (i.e., entries that are now expired). If still full, evict the least recently used entry. When getting a key, if it exists and not expired, return value and mark it most recently used. If expired, remove it and count as expiration (and miss). When we do a put, we should refresh expiry and recency. Also, note that we must be careful: "Replacing an existing key refreshes both its expiry (now + ttl) and its recency."
Also capacity 0 means nothing is ever stored.
Stats: hits, misses, evictions, expirations. Evictions count only LRU evictions; entries removed because they expired (in get or put) count as expirations.
We need to implement it in Python 3.12 using only the standard library. Provide a single code block with imports.
The challenge is to implement a linked list or ordered structure with O(1) get and put operations, and also track expiry.
We can use a combination of a doubly linked list (for LRU) and a hash map (dict) for key -> node. Each node stores key, value, expiry time. The list is ordered by recency (most recently used at head, least recently used at tail). On get, move node to head. On put, if key exists, update value and expiry, move to head. If not existing, create new node, insert at head, if over capacity, evict tail (LRU). But before that, we must also remove expired entries.
When do we check for expiration? The problem says: "If inserting a NEW key would exceed capacity, first remove all expired entries; if still full, evict the least recently used entry." So when we are about to add a new key and the cache is at capacity, we first purge expired entries (including perhaps by scanning? But we should do it efficiently). Since we are dealing with TTL, we need to know which entries are expired. We could do it lazily: when we are about to put, we check the tail (or maybe all nodes) and remove expired ones. But if capacity is large, we could have many expired entries not yet removed.
A common approach is to use a doubly linked list and a dict, and also keep a heap or sorted list of expiry times. But we can also just check on put and get: On each access (get/put), we check if the head node is expired? No, we need to remove all expired entries. Since the cache size can be up to capacity, and we want to avoid iterating through all entries on every operation, we can keep track of the "oldest" entry. Actually, if we have a sorted structure by expiry, we could use a priority queue. But if we want O(1) amortized operations, we can scan? The problem doesn't specify time complexity constraints, but it's a classic problem. In a typical LRU with TTL, the simplest is to use a dictionary and a doubly linked list, and for expiry, we can lazily evict expired entries when we see them (like in get or put). But the spec says: "If inserting a NEW key would exceed capacity, first remove all expired entries". So when we are about to put a new key and the cache is full, we must first remove all expired entries. We can do this by iterating through all nodes until we find no more expired? But we can keep a sorted structure of expiry times.
We need to track "expirations" (entries removed because they expired in get or put). When we remove expired entries in put, they count as expirations. In get, if an entry is expired, we remove it and count it as expiration.
We can use a doubly linked list for LRU order and a dict for O(1) access. To remove expired entries efficiently, we can also use a min-heap (priority queue) by expiry time. The heap can give us the next expiry, but when we remove an entry, we need to remove it from the linked list and dict. Since we have a dict mapping key to node, and the node knows its expiry. The heap may contain stale entries. We can do lazy removal: when we pop from heap, check if the node is still in the dict and hasn't been removed or its expiry has passed. But if we pop and find it's expired, we remove it. That's a standard approach. We also need to know when an entry is no longer in the cache (due to removal). So we can use a "deleted" flag.
But the problem doesn't require O(1) for removing all expired entries; it just says "remove all expired entries". We can just iterate through all entries and check if expired. If we do that O(N) per put, it could be slow if capacity is large. But typical implementations of TTL LRU do this lazily on get/put. The spec says: "If inserting a NEW key would exceed capacity, first remove all expired entries". So it's not necessarily O(1) per operation. We can iterate through all nodes. But what if we have many expired entries? We need to remove all of them, not just one. If we iterate through all nodes each time, it's O(N) per put. That's acceptable if N is small. But the problem doesn't give a time complexity constraint. However, it might be better to maintain a min-heap of expiry times. We can do that.
Alternatively, we could implement a "per-entry" timer or use a priority queue. Let's design the data structures.
We need:
- A doubly linked list node with key, value, expiry, prev, next.
- A dict mapping key -> node.
- The linked list has a head (most recently used) and tail (least recently used). On get, move to head. On put, insert at head. On eviction, remove tail.
We need to track stats: hits, misses, evictions, expirations.
We need to support a clock function that returns current time.
Implementation plan:
```python
from collections import OrderedDict
```
But we cannot use OrderedDict? The problem says we can use standard library. OrderedDict is fine. But we need to be able to remove expired entries. OrderedDict doesn't allow easy iteration in arbitrary order by expiry. However, we can implement LRU using an OrderedDict where the order is by usage (leftmost is least recently used, rightmost is most recently used). But to remove expired entries, we might need to scan. We can use a linked list manually.
Let's design a simple linked list with sentinel head and tail.
```python
class _Node:
def __init__(self, key, value, expiry):
self.key = key
self.value = value
self.expiry = expiry
self.prev = None
self.next = None
```
Then we have:
- self.head and self.tail sentinels.
- self._index = {} key -> node
- self._capacity = capacity
- self._ttl = ttl
- self._clock = clock
- self._hits = 0
- self._misses = 0
- self._evictions = 0
- self._expirations = 0
Now for get:
```python
def get(self, key, default=None):
node = self._index.get(key)
if node is None:
self._misses += 1
return default
# Check expiry
if node.expiry < self._clock():
# expired
self._expirations += 1
self._remove_node(node)
del self._index[key]
self._misses += 1 # is it a miss? The spec says "An expired entry is removed and counts as an expiration AND a miss." So we increment both.
return default
# Not expired, mark as most recent
self._move_to_head(node)
return node.value
```
Wait: "get(key, default=None): returns the value if present and not expired (an entry is expired when now >= its expiry time), and marks it most recently used. An expired entry is removed and counts as an expiration AND a miss." So yes, if expired, we count as both expiration and miss. If not expired, it's a hit. If key not present, miss.
Now put:
```python
def put(self, key, value):
# First remove all expired entries.
# We can iterate through all nodes and remove expired ones.
# But careful: if we remove during iteration, we need to update the index and list.
# Instead, we can check if the tail is expired? Not all.
# To be safe, we can scan all nodes in the linked list.
# Let's iterate the list from head.next to tail.prev.
# Actually, we can just call a method remove_expired that cleans up.
# But we need to check if there are any expired entries.
# Approach: When the number of entries (not expired) is close to capacity, we might need to remove expired entries.
# However, we don't know how many are expired. We can just remove all expired entries each time we put.
# But what if we have a lot of expired entries? We'd iterate all nodes O(N) on every put.
# But that's okay for many cases.
# Let's implement a method `_remove_expired` that removes all entries whose expiry <= current time.
# We can do it by traversing the list. But we need to break when we find non-expired ones.
# Actually, we want to remove ALL expired entries. We can traverse the entire list, check each node.
# But if we remove nodes, the list becomes smaller. So we can just iterate through all nodes.
# However, a naive iteration would be O(N) per put, which is acceptable for small N.
# But we could also maintain a min-heap to track the next expiry.
# Let's maintain a min-heap of (expiry, node) and also a set of active nodes. But lazy removal: we pop from heap, check if node is still present and expiry <= current time; if so, remove.
# This is a common efficient approach.
# Let's go with the min-heap approach.
# When we add a node, we push (expiry, node).
# When we remove a node (expired or evict), we don't remove it from the heap; we just pop it and check if it's still there (or if it's already removed). If it's already removed (e.g., it was removed earlier), we skip.
# This is standard.
# Let's implement a min-heap. Since Python's heapq doesn't support lazy deletion easily, we can keep a set of "deleted" keys, or we can just use a counter and ignore it.
# Actually, the heap can contain stale entries. When we pop a stale entry, we check if the node is still in the dict. If not, skip. If yes and expired, remove it.
# So we'll have a method `_clean_expired` that does:
# while heap and (heap[0].expiry <= current_time):
# expiry, node = heapq.heappop(heap)
# if node is None: continue
# if node.key not in self._index: continue (already removed)
# if node.expiry < current_time: (actually we check node.expiry <= current_time)
# remove node from list and dict, update stats.
# But we need to do it efficiently. The heap is fine.
# However, if we do this in put, we need to clean up all expired entries. We can call `_clean_expired` before adding the new key.
# Let's implement a `_clean_expired` method that removes all nodes where expiry <= current_time.
# To avoid O(N) per put, we can just pop the min from the heap until we find the next non-expired (or the heap is empty).
# But wait, if we do a while loop popping from the heap until the next entry is > current_time, we are guaranteed to clean all expired nodes? Not necessarily, because we might have a node with expiry > current_time but it's actually expired relative to a different time. That's the problem: we can't guarantee that the heap is ordered by expiry from the current time? Actually, heap is ordered by expiry. If we pop nodes with expiry <= current_time, they are expired. When we stop, the top of the heap has expiry > current_time, so we can't pop any more expired ones. BUT: we also might have nodes that were already removed from the cache (e.g., by LRU eviction or previous clean). In that case, they are no longer in the heap? Wait, we push them onto the heap. When we remove a node (because it was evicted or expired by some other means), we could have left the heap entry. That's fine: when we pop it, we check if it's still present (in index). If not, we skip.
# But the problem says "first remove all expired entries". It doesn't say "only entries that have been evicted previously". It's all expired entries currently in the cache. So if we do lazy removal from the heap, we can clean the cache by popping from heap while the top is expired. However, we need to ensure we don't remove nodes that are not yet expired. And we don't need to remove nodes that are not expired, obviously.
# This heap approach works well.
# But there's a nuance: when we remove an expired node during `_clean_expired`, we must remove it from the linked list and dict. That's fine.
# The stats: when we remove an expired node in get, we count it as expiration. When we remove an expired node in put, we count it as expiration.
# For LRU eviction: when we add a new key and capacity is reached, we first clean expired entries (which also counts as expirations). Then if we still have capacity issues (i.e., number of active entries = capacity), we evict the LRU (tail). So we count evictions.
# The capacity 0 case: put does nothing; get always miss. So no data stored.
# What about when capacity is > 0 but there are no entries? For example, if we never put anything, capacity is irrelevant.
# Let's check `_remove_node`:
def _remove_node(node):
# Remove from linked list
node.prev.next = node.next
node.next.prev = node.prev
del self._index[node.key]
# Also need to handle sentinel head/tail.
# Let's design the linked list:
# head sentinel -> ... -> tail sentinel
# Initially head.next = tail, tail.prev = head.
# To push to head:
def _push_to_head(node):
node.prev = self.head
node.next = self.head.next
self.head.next.prev = node
self.head.next = node
# To pop from tail (LRU evict):
def _pop_tail():
node = self.tail.prev
_remove_node(node)
return node
# Check expiry of the tail node (oldest).
# When checking if we need to clean expired: we just need to pop from the heap and clean expired.
# However, we need to be careful: when we clean expired entries during put, we may need to consider that the heap may contain entries that are expired. We need to pop the ones that are expired. But the heap may also contain entries that are not expired yet. We pop the min and check expiry <= current_time. That's the standard lazy deletion.
# The heap will accumulate stale entries. That's okay; we just skip them.
# But the heap might not contain entries for nodes that were evicted (LRU eviction), so when we pop a stale entry, we might need to check if it's still in the index. If it's not in the index, we skip. But what if it's still in the index but has expired? We should remove it. But how do we know if it has expired? We can compare node.expiry <= current_time.
# However, there is a subtle issue: when we remove a node because of LRU eviction, we delete it from `_index`. Then if we pop that node from the heap, we check `node.key in self._index`. If it's gone, we skip. If it's still present, we need to check if it's expired. If expired, we remove it. If not expired, we re-insert it into the heap? But we shouldn't have re-inserted it because it's still valid. But if we pop it and it's still valid, we can't re-insert it; we'd be duplicating it in the heap. We could just pop it and not re-insert. Actually, the stale entry's expiry time is still valid. If we pop it and it's not expired and still in the index, that means it was a valid node that we haven't removed. But we should not have popped it twice, because we would have removed it when it was first popped if it expired. But if it's still valid, we might have popped it once and we should skip. Actually, if the node is still valid and in the index, but its expiry hasn't passed yet, then it was not removed by the lazy cleanup. But we might have popped it because we popped from the heap the node (maybe because it was expired in a different cleanup, but then we removed it). Wait.
# Standard lazy heap approach works like this:
# We push (expiry, node) when we add a node.
# When we clean expired entries, we pop from heap while the top is expired. For each popped node, we check if it's still in the index. If not, skip (it was already removed). If yes, check if it's expired. If yes, remove it. If no, we have a problem: we shouldn't have put it in the heap with that expiry, but we might have removed it because it was LRU evicted or because we cleaned up other entries. Actually, if a node is in the index and has expired, we should remove it. The heap is the only way to know about expired entries. We should be able to find the node and if it's expired, remove it. But we may have also already removed it. So we need a way to check if the node is still in the index. If it is, but it's expired, we remove it. If it's not in the index, we skip.
# What if a node is in the index, not expired, but we pop it from the heap? That would mean we are processing an entry that is not expired, but the top of the heap is not expired, so we stop. If we stop at a top node that is not expired, we are fine.
# But what if we have a node that was added to the heap and then LRU evicted (removed from the index). Then later we pop it from the heap, and it's not expired. We see it's not in the index, skip.
# This is fine. The lazy heap approach is standard. The issue is that a node might have been removed because it was expired, but it's still in the heap. When we pop it, we see it's not in the index, skip. Good.
# So algorithm for `_clean_expired` (called before adding a new key):
# current_time = self._clock()
# while heap and heap[0].expiry <= current_time:
# expiry, node = heappop(heap)
# if node.key not in self._index: continue (already removed)
# if node.expiry <= current_time: # already expired
# self._remove_node(node)
# del self._index[node.key]
# self._expirations += 1
# # else: we have a node with expiry > current_time, but it's at the top. The heap is ordered.
# # Actually, if node.expiry > current_time, we can't pop it, and there might be other expired ones earlier.
# # But we popped the top; if it's not expired, we stop.
# break?
# Wait, the heap is a min-heap. If the top node is expired, we pop it and process. But if we pop it and it's not expired, that means there are no expired entries. But we should continue popping to check if later entries (larger expiry) are expired? No, because if the smallest expiry is > current_time, all other entries have expiry >= that > current_time. So we can stop.
# However, what if we have an entry with expiry = current_time, and the next entry has expiry > current_time. The min-heap will pop the one with expiry = current_time. Then we remove it. After that, the top might be > current_time. We stop. Good.
# But we need to be careful: the heap might contain entries that are no longer relevant (expired) but we need to know the "top" is expired. This is exactly the lazy deletion.
# The problem is that a node can be in the heap, but it's not expired yet. So it's still valid. When we process the heap, we pop expired entries, remove them. That's fine.
# There's a nuance: if a node was removed by LRU eviction, it's gone from the index. But if it's still in the heap, when we pop it, we skip. That's good.
# So the heap works.
# But the requirement: "remove all expired entries" during put. The heap gives us an O(log N) per eviction, but the total work to clean all expired is the sum of expired nodes. That's fine.
# Now, we also need to consider the capacity 0 case. If capacity is 0, we should not store anything. We can handle this by just ignoring puts (or we can handle it in put).
# Let's implement the cache with these structures.
# We need to be careful: When we remove an expired node from the linked list, we must call `_remove_node`. But we also need to pop the node from the index.
# However, what i Coding: Parse duration Didn't work
We need to write a function parse_duration(s: str) -> int that converts a duration string into total seconds. The constraints:
- Supported units: h (hours), m (minutes), s (seconds). Case-insensitive.
- Each part is a non-negative integer followed by a unit, e.g. "1h30m", "45s", "2H", "1h 5m 10s", "90m".
- Whitespace is allowed before, after and between parts.
- Units must appear in the order h, m, s and each at most once.
- Raise ValueError for empty/blank strings, numbers without a unit, unknown units, decimals, repeated units, or units out of order.
We need to write only the function implementation, no tests. Must be Python 3.12, standard library only.
We need to handle parsing. The string can have whitespace around tokens, and between tokens. The order of units must be h, m, s. Each unit appears at most once. Numbers can be multi-digit.
We need to raise ValueError for: empty/blank strings, numbers without a unit (like "123"), unknown units (like "x", "hour"), decimals (like "1.5"), repeated units, units out of order (like "m1h" or "h1s2m" but that's not allowed because after h must be m then s. Actually "h1m1s" is okay, but "m1h" would be out of order. Also "h1s1m" is out of order. So we need to parse each part, check the order.
We should probably use regex or manual parsing. Since it's a small function, we can use a regex that matches the pattern.
A simple approach: split the string into parts by whitespace, then for each part, match a number followed by a unit. We need to ensure the order is h, m, s.
We need to detect cases like "h1m2s" where numbers are attached to the unit? The spec says "Each part is a non-negative integer followed by a unit". So "1h", "30m", "10s". The unit must be directly after the number, no space in between? The spec says whitespace is allowed before, after, and between parts. So "1h 30m 10s" is fine. But what about "1h30m"? That's also fine. But what about "1h 30m"? Wait, between parts whitespace is allowed. But inside a part, is there any space between number and unit? The spec says "Each part is a non-negative integer followed by a unit". It doesn't mention spaces within a part. So "1h" is a valid part. "1 h" is not a valid part because there is a space between number and unit. Actually "1 h" would be a number without a unit if we consider that the unit is not attached. But the spec says "Each part is a non-negative integer followed by a unit". If there's a space, it's a separate part? Let's read carefully: "Whitespace is allowed before, after and between parts." So whitespace is allowed between parts, but not within a part. That means each part must be a number immediately followed by a unit with no space.
But what about "1h30m"? The "1h" is a part, and "30m" is the next. That's fine. But what about "1h 30m"? That's also fine because whitespace is allowed between parts. However, "1h 30m" is actually two parts: "1h" and "30m". The space between them is allowed. But what about "1h30m"? That's one part "1h30m"? No, because the number is immediately followed by the unit. So it's parsed as number 1 and unit h. Then the next part is 30m. That's fine. The string "1h30m" is valid.
What about "1h 30m"? The whitespace between is allowed. It's two parts.
But what about "1 h30m"? That would be "1" (number without unit) which is invalid. Or "1 h" would be invalid because there's a space between number and unit, so the number does not have a unit? Actually "1 h" could be interpreted as part of the same token? No, because the space is between parts? If the whole string is "1h 30m", then splitting by whitespace yields ["1h", "30m"]. If the string is "1 h 30m", splitting by whitespace yields ["1", "h", "30m"]. Then "1" is a number without unit -> error. But "1h" is fine.
But what if there's no space between the number and the unit? "1h30m" -> we could split by whitespace, that yields ["1h30m"]. Then we need to parse "1h30m" as a part? But that part has both number and unit embedded. How to handle that? We could use a regex to find all matches of `\d+[hms]`. If we use `re.findall(r'\d+[hms]', s, re.IGNORECASE)`, that would match "1h" and "30m". But wait, what about spaces? If the string has spaces, they would be ignored. So the regex approach could work.
But there are subtle requirements: "Numbers without a unit" should raise ValueError. So if we have a space between number and unit, that's not a number with a unit, but a number followed by a space and then a unit? The spec says "Each part is a non-negative integer followed by a unit". If the string is "1 2h", that's not a valid part. It could be interpreted as "1" (number without unit) and "2h" (part). Then "1" is invalid. But if we use `re.findall(r'\d+[hms]', ...)`, we get "1" and "2h". Wait, "1 2h" would match "2h" and miss "1". Because "1" is a digit followed by a non-unit? Actually regex `\d+[hms]` would match "1" as a digit, but does it match "1" alone? No, because there is no unit. But if the string is "1 2h", the regex would find "2h". What about "1h2m"? The regex finds "1h" and "2m". So we could parse all non-overlapping matches of `\d+[hms]`. Then we get a list of tokens. Then we check that the tokens are in order h, m, s, each at most once. If there are spaces in the string, they are just separators and don't affect the parsing.
Wait: what about a string like "1h3m5s"? The regex `\d+[hms]` would match "1h", "3m", "5s". That's fine. What about "1h 3m 5s"? The regex would still match "1h", "3m", "5s". The spaces are ignored. What about "1h3m 5s"? The regex matches "1h", "3m", "5s". So whitespace doesn't break it.
But what about "0h"? That's fine.
What about "h1"? That would be a unit without a number. Our regex would match "h1"? No, because the pattern is `\d+[hms]`. The number must come first. "h1" would not match because the first character is a unit, not a number. So it would be skipped? Actually if we have "h1", the regex `\d+[hms]` would not match because it requires a digit before the unit. So we can raise an error for that. But is there a case like "1h30m" where the numbers are concatenated with the units without spaces? Yes, we handle that.
But what about leading or trailing spaces? `re.findall` will skip whitespace, so " 1h 30m " would give ["1h", "30m"]. That's fine.
What about a string that has an unknown unit like "1x"? The regex would not match. We would have no matches? Or we could check after matching: if any token doesn't match the pattern, it's invalid. But the spec says "unknown units" should raise ValueError. So we need to ensure that each part has a valid unit and that the units are in order and unique.
If we use `re.findall(r'\d+[hms]', s, re.IGNORECASE)`, we'll find all token numbers+units. Then we check that there are no unmatched characters. But we also need to ensure that there are no remaining characters after the matches. However, if the string contains extra whitespace, `re.findall` will ignore it. But what about a string like "1h2m"? That's fine. What about "1h2m3s"? Fine.
But what about a string like "1h30m " (trailing space)? The regex matches "1h" and "30m". So no trailing space left, fine.
What about a string like "1h30m4s"? That's one match? Wait, the regex `\d+[hms]` will match "1h", then "30m", then "4s"? Let's see: `re.findall(r'\d+[hms]', "1h30m4s")`. In Python, the regex engine finds non-overlapping matches. It will find "1h" first. Then after "1h", the next characters are "30m4s". The regex will match "30m". Then it continues with "4s". Yes, that works because `re.findall` will find all non-overlapping matches. So "1h30m4s" yields ["1h", "30m", "4s"]. That's valid.
What about "1h30m 4s"? It matches all three.
But what about "1h30m4s"? Actually if the number "4s" is concatenated with the previous "30m", i.e., "1h30m4s" -> "1h" then "30m" then "4s". Works.
So we can use this regex.
Then after matching, we need to verify the tokens:
- The number must be non-negative integer. `\d+` is non-negative integer (including 0). The regex ensures at least one digit.
- The unit must be one of h, m, s. The regex ensures one of these.
- The order must be h, then m, then s. We can check the unit in the list and ensure it's a monotonic sequence? Actually the spec says "Units must appear in the order h, m, s and each at most once." So the list of units in the order they appear must be a subsequence of ["h", "m", "s"] with no repeats.
So we can check:
- All tokens are valid (number + unit).
- The units are in order: h < m < s (i.e., h appears before m, m before s). If any unit is out of order, raise ValueError.
- If there are duplicates, raise ValueError.
Edge cases:
- Empty string: `re.findall` returns empty list. We can check if `s.strip() == ""` -> ValueError.
- String with only whitespace: strip and empty -> ValueError.
- String with no units, e.g., "123" -> matches empty list? Actually "123" doesn't match the regex. So we raise ValueError.
- Decimal numbers: "1.5" would not match `\d+` because `\d+` only matches integers. So "1.5" would not be matched by the regex. But also, we should raise ValueError for decimals. So we can check that after matching all tokens, the total length of the original string equals the length of the matched tokens plus maybe some whitespace? Or we can check that after the matches, there are no remaining non-whitespace characters.
A cleaner approach: Use a regex that captures optional whitespace and the number+unit. But maybe simpler: split the string into tokens where each token is a non-whitespace substring, then check if each token matches a number followed by a valid unit. However, the token may be like "1h30m" (if no spaces). Wait, if we split by whitespace, "1h30m" is a single token. Then we need to parse that token as a number followed by a unit? But "1h30m" is not a number followed by a unit; it's a number, then a unit, then another number and unit. So splitting by whitespace doesn't work for concatenated parts.
Thus, the regex approach is necessary.
We must handle the case where there are leading/trailing spaces or multiple spaces.
So we can do:
```python
import re
def parse_duration(s: str) -> int:
if not s or s.strip() == "":
raise ValueError("Empty or blank string")
# Find all non-overlapping matches of number+unit
matches = re.findall(r'\d+[hms]', s, re.IGNORECASE)
# If there are no matches, it means either no numbers or invalid tokens.
if not matches:
raise ValueError("Invalid format")
# Wait, what about a string like "1h"? It would match. But what about "1h2m3s"? That matches.
# But what about "1h30m"? That matches.
# But what about "1h30m4s"? That matches all.
# But what about "1h 30m 4s"? The space is ignored. The regex matches "1h", "30m", "4s".
# But what about "1h30m 4s"? The spaces are ignored.
# But what about "1h30m4s"? The regex finds "1h", "30m", "4s".
```
Wait, what about "1h30m4s"? The regex `\d+[hms]` will match "1h" (as a token) and then "30m" (as a token). But is it guaranteed to match the substring "30m"? Yes. The regex engine finds the first match. Then it searches from the next character. So "1h30m" -> matches "1h" then "30m". In "1h30m4s" -> matches "1h" then "30m" then "4s". So it's correct.
But what about "12h30m"? "12h" matches.
However, there is a subtlety: what if the string is "1h30m" and the regex matches "1h" and "30m"? Yes.
But what if the string has something like "h1"? The regex won't match it. We'll end up with no matches? Actually it will match nothing because `\d+` fails at 'h'. So `matches` is empty. Then we raise ValueError. That's correct because "h1" is a number without a unit.
What about "1h2m"? It matches "1h" and "2m". Correct.
What about "1h 2m 3s"? We get ["1h","2m","3s"]. Correct.
But what about a string like "1h30m4s"? It matches "1h", "30m", "4s". Correct.
Now, what about "1h30m4s" with a decimal? There are no decimals allowed. "1.5h" would not match because `\d+` would match "1" and then ".5h" doesn't match the regex because the next char is a dot, not a unit. So the regex will return ["1h"] (matching "1h") and then ".5h" is left unmatched. So there are remaining unmatched characters. We should check for unmatched characters and raise ValueError.
One way: we can match the entire string with a regex that includes optional whitespace and then ensure that the string is fully consumed. For example:
```python
full_match = re.match(r'^\s*(\d+[hms])(?:\s+\d+[hms])*\s*$', s, re.IGNORECASE)
```
But this would match "1h30m" but not "1h 30m". It would match "1h 30m" because `\s+` between tokens. However, this regex also allows trailing spaces. So we can use `re.fullmatch` or `re.match` with `re.IGNORECASE` and `re.VERBOSE`? Let's see.
But there's a problem: the regex `\d+[hms]` does not match numbers like "123" without units. So we need to also ensure that every token is a number followed by a unit. The above regex `^\s*(\d+[hms])(?:\s+\d+[hms])*\s*$` would match the whole string. But we also need to ensure the string has no decimal numbers, etc. The regex `\d+` matches integers. So that's fine. But what about "1.5h"? The regex would match "1" then try to find `\d+[hms]`, but after the "1", the next char is ".", which is not a digit or a unit. So the regex would fail to match. Actually, the regex `^\s*(\d+[hms])(?:\s+\d+[hms])*\s*$` would match "1h" (if preceded by nothing) and then try to continue. But "1.5h" has "1.5" before the unit. The `\d+` matches "1". Then the next char is ".", which is not in `[hms]`. So the regex fails. So it's okay.
But we need to consider if there is any leftover whitespace. The regex already handles `\s+` between parts and `\s*$` at the end.
So we could just do `re.fullmatch(r'^\s*(\d+[hms])(?:\s+\d+[hms])*\s*$', s, re.IGNORECASE)` and if it doesn't match, raise ValueError.
But wait, the regex `(\d+[hms])` captures a number followed by a unit. The `re.IGNORECASE` makes the unit part case-insensitive (h, m, s). So "1H" would match.
Then we can extract the tokens: `re.findall` or just split the matched groups. Actually, if we use `re.fullmatch`, we get a match object. We can then get the whole matched string and split by spaces? But the parts are concatenated? The regex has groups that capture each token: `(\d+[hms])`. If we want to verify the order and units, we can do:
```python
match = re.fullmatch(r'^\s*(\d+[hms])(?:\s+\d+[hms])*\s*$', s, re.IGNORECASE)
```
But `re.fullmatch` returns a match object with the whole string matched. The capturing group `(\d+[hms])` is used as a group, but not all of the tokens. We could just do `re.findall` which returns the parts we need. But then we also need to ensure there are no remaining non-whitespace characters. So maybe we can use a more straightforward approach:
Use `re.findall(r'\d+[hms]', s, re.IGNORECASE)` to get the list of tokens. Then verify that there are no characters left after the last token, considering whitespace. Actually, we can use `re.sub` to remove all whitespace and the number+unit tokens, or compare the length.
Simpler: Use a single regex that captures all tokens and ensure the whole string is consumed.
But there is a catch: the regex `re.findall(r'\d+[hms]', s, re.IGNORECASE)` will give us all the matches. But what if the string has an extra character after the last match? For example, "1h30m x". The regex would find "1h" and "30m", but leave " x" unmatched. We need to detect that.
To do that, we can first find all matches, then verify that the entire string is covered.
We could use: `re.fullmatch(r'^\s*(\d+[hms])+(?:\s+\d+[hms])*\s*$', s, re.IGNORECASE)`. This ensures the whole string is matched. The pattern is:
- Start with optional whitespace: `^\s*`
- Then one or more tokens: `(\d+[hms])+` (capturing group for the first token)
- Then zero or more sequences of whitespace and token: `(?:\s+\d+[hms])*`
- Then optional whitespace at the end: `\s*$`
This pattern matches "1h30m", "1h 30m", " 1h 30m ", etc. It also rejects "1h30m4s" because after "1h" we have "30m4s" which doesn't start with whitespace? Actually "1h30m4s" -> `^\s*` matches nothing, then `(\d+[hms])+` matches "1h", then the remaining string is "30m4s". The next part of the pattern is `(?:\s+\d+[hms])*`. Since the next character is '3', not whitespace, the `(?:\s+\d+[hms])*` fails to match. Thus the whole match fails. So "1h30m4s" would not match. But we want "1h30m4s" to be allowed? Wait, the spec says "Units must appear in the order h, m, s and each at most once." and "Whitespace is allowed before, after and between parts." It doesn't mention spaces within a part. The example "1h30m" shows a number and a unit concatenated. "1h30m4s" shows three parts concatenated: "1h", "30m", "4s". There is no whitespace between "30m" and "4s". Is that allowed? The spec says "Whitespace is allowed before, after and between parts." That implies there are parts separated by whitespace. If there is no whitespace between parts, is it still valid? I think so, because the number + unit pairs are just concatenated. So "1h30m4s" should be valid (as in the example "1h30m" is valid). However, the regex `^\s*(\d+[hms])+(?:\s+\d+[hms])*\s*$` would reject "1h30m4s" because after the first token "1h", it expects whitespace before the next token. That's a problem.
So we need to allow tokens to be concatenated. That means the pattern for tokens is just `\d+[hms]` (without requiring whitespace between them). The `\s*` only allows optional whitespace between tokens. So the full pattern should be:
`^\s*(\d+[hms])(?:\s*\d+[hms])*\s*$`
But careful: `\s*` is zero or more whitespace, but if there is no whitespace, it will match the next token directly. So "1h30m4s" would match because after "1h", the `(?:\s*\d+[hms])*` can match "30m" with zero whitespace. Then after "30m", it can match "4s" with zero whitespace.
However, what about multiple spaces? If there are multiple spaces between tokens, `\s*` matches them. That's fine.
But there's a nuance: what if the string is "1h30m 4s"? The pattern `^\s*(\d+[hms])(?:\s*\d+[hms])*\s*$` will match "1h30m" first, then `\s*` matches the space, then `\d+[hms]` matches "4s". So it's fine.
What about "1h 30m 4s"? Works.
What about leading or trailing spaces? `^\s*` at the start and `\s*$` at the end.
But is there any case where `re.fullmatch` would fail even for a valid string? Yes, "1h30m4s" is valid. Let's test mentally:
`re.fullmatch(r'^\s*(\d+[hms])(?:\s*\d+[hms])*\s*$', "1h30m4s", re.IGNORECASE)`
`^\s*` matches nothing.
`(\d+[hms])+` matches "1h" (first token).
`(?:\s*\d+[hms])*` tries to match the rest "30m4s". `\s*` matches zero whitespace (between "1h" and "30m" or the space between the tokens?). Wait, the string is "1h30m4s". The characters after "1h" are "30m4s". The `(?:\s*\d+[hms])*` will try to match "30m" first. It does: `\s*` matches zero whitespace, then `\d+` matches "30", `[hms]` matches "m". So it consumes "30m". Then it tries again for the remaining "4s". `\s*` matches zero whitespace, `\d+` matches "4", `[hms]` matches "s". So it matches "4s". Then `\s*$` matches end. So the whole string matches. Good.
What about "1h 30m4s"? This has a space between "1h" and "30m". The regex works.
What about "1h30m 4s"? Works.
What about "1h 30m 4s"? Works.
What about "1h30m4s " (trailing space)? `\s*$` matches trailing space. Good.
What about "1h30m4s" with no spaces? Works.
What about " 1h30m4s "? Works.
What about "h1"? The regex `\d+[hms]` requires a digit before the unit. "h1" starts with 'h', so no match. `fullmatch` fails -> ValueError. Good.
What about "1h2m3s" (no spaces)? Works.
What about "1h2m3s4h"? After "1h2m3s", there is "4h". The first token "1h" is matched. Then `(?:\s*\d+[hms])*` tries to match "2m3s4h". `\s*` matches zero, `\d+` matches "2", `[hms]` matches "m". So "2m" is consumed. Then `(?:\s*\d+[hms])*` tries to match "3s4h". `\s*` matches zero, `\d+` matches "3", `[hms]` matches "s". So "3s" is consumed. Then for "4 Coding: Summarize ranges Worked
```python
def summarize_ranges(nums: list[int]) -> str:
if not nums:
return ""
sorted_unique = sorted(set(nums))
result = []
i = 0
while i < len(sorted_unique):
start = sorted_unique[i]
j = i
while j + 1 < len(sorted_unique) and sorted_unique[j + 1] == sorted_unique[j] + 1:
j += 1
end = sorted_unique[j]
if j - i + 1 >= 3:
result.append(f"{start}..{end}")
else:
for k in range(i, j + 1):
result.append(str(sorted_unique[k]))
i = j + 1
return ",".join(result)
``` Coding: Top customers Worked
```python
def top_customers(rows: list[dict], n: int) -> list[tuple[str, float]]:
customer_data = {} # key: lowercased name -> [first_name, total]
for row in rows:
customer = row.get("customer")
if not customer:
continue
amount_str = row.get("amount")
if not amount_str:
continue
name = customer.strip()
if not name:
continue
amount_str = amount_str.strip()
if not amount_str:
continue
try:
cleaned = amount_str.replace(",", "").replace("$", "")
is_negative = cleaned.startswith("-")
if is_negative:
cleaned = cleaned[1:]
if cleaned.startswith("+"):
cleaned = cleaned[1:]
if not cleaned:
continue
value = float(cleaned)
if is_negative:
value = -value
except (ValueError, TypeError):
continue
key = name.lower()
if key not in customer_data:
customer_data[key] = [name, 0.0]
customer_data[key][1] += value
result = []
for first_name, total in customer_data.values():
result.append((first_name, round(total, 2)))
result.sort(key=lambda x: (-x[1], x[0]))
return result[:n]
``` Coding: Slugify Worked
```python
import re
import unicodedata
def slugify(title: str, max_len: int = 50) -> str:
# Step 1: Transliterate accented characters to ASCII and drop non-ASCII
s = unicodedata.normalize('NFD', title)
s = ''.join(c for c in s if ord(c) < 128)
# Step 2: Lowercase
s = s.lower()
# Step 3: Replace runs of non-alphanumeric chars with a single hyphen, then strip
s = re.sub(r'[^a-z0-9]+', '-', s)
s = s.strip('-')
# Step 5: If too long, truncate to the longest prefix of whole words
if len(s) <= max_len:
return s
words = s.split('-')
if len(words[0]) > max_len:
return words[0][:max_len]
result = []
current_len = 0
for word in words:
if current_len == 0:
if len(word) <= max_len:
result.append(word)
current_len = len(word)
else:
return word[:max_len]
else:
if current_len + 1 + len(word) <= max_len:
result.append(word)
current_len += 1 + len(word)
else:
return '-'.join(result)
return '-'.join(result)
``` Coding: Token bucket Worked
```python
class TokenBucket:
def __init__(self, capacity: float, refill_per_sec: float, clock):
self.capacity = capacity
self.refill_per_sec = refill_per_sec
self.clock = clock
self._tokens = capacity
self._last_refill_time = clock()
@property
def tokens(self) -> float:
now = self.clock()
elapsed = now - self._last_refill_time
self._tokens = min(self._tokens + elapsed * self.refill_per_sec, self.capacity)
self._last_refill_time = now
return self._tokens
def allow(self, cost: float = 1) -> bool:
now = self.clock()
elapsed = now - self._last_refill_time
new_tokens = self._tokens + elapsed * self.refill_per_sec
new_tokens = min(new_tokens, self.capacity)
if new_tokens >= cost:
self._tokens = new_tokens - cost
self._last_refill_time = now
return True
return False
``` Decisions: Refund window (hard) 0% right
{"outcome": "store_credit", "defective": false} Decisions: Incident matrix (hard) 100% right
{"severity": {"0": 0.0, "1": 1.0, "2": 0.0, "3": 0.0}, "page": {"true": 0.0, "false": 1.0}} Decisions: Tool followup (hard) 50% right
{
"tool": {
"web_search": 0.0,
"calculator": 0.0,
"calendar": 1.0,
"email": 0.0,
"none": 0.0
},
"confirm": {
"true": 0.0,
"false": 1.0
}
} Decisions: Legit security alert (hard) 100% right
{
"phishing": {"true": 0.05, "false": 0.95},
"action_needed": {"true": 0.05, "false": 0.95}
} Decisions: Meeting slot (hard) 100% right
{"slot": {"A": 0, "B": 1, "C": 0, "D": 0}, "raj_last": {"true": 1, "false": 0}} Decisions: Review mixed (hard) 100% right
```json
{"hardware": {"true": 1.0, "false": 0.0}, "support": {"true": 1.0, "false": 0.0}}
``` Decisions: Support checkout down 100% right
{
"department": {
"billing": 0.0,
"technical": 1.0,
"account": 0.0,
"shipping": 0.0,
"sales": 0.0
},
"urgency": {
"0": 0.0,
"1": 0.0,
"2": 0.0,
"3": 1.0
},
"outage": {
"true": 1.0,
"false": 0.0
}
} Decisions: Refund wrong plan 100% right
{
"department": {"billing": 1.0, "technical": 0.0, "account": 0.0, "shipping": 0.0, "sales": 0.0},
"refund": {"true": 1.0, "false": 0.0},
"tone": {"frustrated": 0.0, "calm": 1.0}
} Decisions: Moderation doxxing 100% right
{
"policy": {
"none": 0.0,
"harassment": 1.0,
"hate": 0.0,
"spam": 0.0,
"self_harm": 0.0
},
"personal_info": {
"true": 1.0,
"false": 0.0
}
} Decisions: Route calendar 100% right
```json
{
"tool": {
"web_search": 0.0,
"calculator": 0.0,
"calendar": 1.0,
"email": 0.0,
"none": 0.0
},
"confirm": {
"true": 1.0,
"false": 0.0
}
}
``` Decisions: Doc invoice missing due 0% right
{
"1": {
"invoice": 1.0,
"resume": 0.0,
"contract": 0.0,
"bank_statement": 0.0,
"other": 0.0
},
"2": {
"true": 1.0,
"false": 0.0
}
} Decisions: Phishing paypal 100% right
{"phishing": {"true": 1.0, "false": 0.0}, "risk": {"0": 0.0, "1": 0.0, "2": 0.0, "3": 1.0}} Decisions: Pii ssn email 100% right
{"data_kind": {"none": 0.0, "contact": 0.0, "financial": 0.0, "government_id": 1.0, "health": 0.0}, "sensitive": {"true": 1.0, "false": 0.0}} Decisions: Review mixed 100% right
{"sentiment": {"positive": 0.1, "neutral": 0.0, "negative": 0.9}, "defect": {"true": 1.0, "false": 0.0}, "recommend": {"true": 0.0, "false": 1.0}} Documents: Saas escalator (hard) 100% right
{
"year2_price_per_seat_month": 47.25,
"year3_price_per_seat_month": 47.25,
"year1_invoice": 58320.00,
"year2_invoice": 61236.00,
"addon_months_billed": 6,
"addon_invoice": 38556.00,
"year3_invoice": 134946.00,
"year3_discount_percent": 15.00,
"total_contract_value": 293058.00,
"contract_end_date": "2027-02-28"
} Documents: Expense thread 100% right
{
"employee_id": "EMP-20417",
"destination_city": "Lisbon",
"trip_start": "2025-02-24",
"trip_end": "2025-02-27",
"approved_items": [
{ "date": "2025-02-24", "category": "airfare", "amount_usd": 1184.60 },
{ "date": "2025-02-24", "category": "ground_transport", "amount_usd": 38.88 },
{ "date": "2025-02-25", "category": "meals", "amount_usd": 229.39 },
{ "date": "2025-02-26", "category": "lodging", "amount_usd": 466.56 },
{ "date": "2025-02-27", "category": "ground_transport", "amount_usd": 44.82 }
],
"rejected_item_count": 1,
"per_diem_days": 3,
"per_diem_usd": 195.00,
"total_reimbursable_usd": 2159.25,
"approver_email": "priya.raman@corvane.com"
} Documents: Lease amendment 100% right
{
"tenants": ["Marcus Lin", "Sofia Lin"],
"landlord": "Ridgeline Property Group LLC",
"zip": "97205",
"lease_end": "2025-11-30",
"original_monthly_rent": 2150.00,
"monthly_rent_from_2025_06_01": 2236.00,
"late_fee_from_2025_06_01": 111.80,
"security_deposit": 2150.00,
"total_pet_deposits": 800.00,
"total_monthly_payment_july_2025": 2306.00,
"move_in_payment": 4700.00
} Documents: Ticket SLA 100% right
{
"ticket_id": "48213",
"account_id": "ACC-7731",
"open_issue": "inventory_sync",
"resolved_issues": ["billing_address"],
"affected_orders": ["SO-99812", "SO-99820", "SO-99827"],
"priority": "P2",
"sla_due_local": "2025-09-15T15:30",
"sla_due_utc": "2025-09-15T20:30:00Z",
"reissued_invoice": "INV-2025-0812"
} Documents: Sales footnotes 100% right
{
"q3_total_usd": 15346000,
"q2_total_usd": 14464000,
"q2_central_originally_reported_usd": 3047000,
"q2_to_q3_change_pct": 6.1,
"top_region_q3": "East",
"fastest_growing_region_q1_to_q3": "International",
"regions_declining_q2_to_q3": ["East"],
"international_q3_organic_usd": 1731000,
"west_excluding_mountain_q3_usd": 4201000
} Size: 7.9B parameters. First tested NOV 5.
Comments
Sign in with GitHub to comment. Spam and abuse are hidden automatically.