easy +10 pts

Parse bit field flags

Decode a packed integer into a dictionary of named boolean flags.

You are given a bit field packed into a non-negative integer. Each bit position corresponds to a flag with a specific name, as defined by the given mapping. The mapping is a dict that maps each flag name to its bit position (0-based, from least significant bit). Write a function `parse_flags(packed: int, mapping: dict) -> dict` that returns a new dict with the same keys as in `mapping`. The value for each key is `True` if the corresponding bit is set in `packed`, and `False` otherwise. For example, if `mapping = {'debug': 0, 'verbose': 3}` and `packed = 9` (binary 1001), then bit 0 is set (True) and bit 3 is set (True) because 9 = 2^0 + 2^3. The result is `{'debug': True, 'verbose': True}`. You may assume: - `packed` is a non-negative integer. - `mapping` keys are strings, values are non-negative integers (bit positions). - The mapping may contain any number of entries. Do not modify the input mapping; return a new dictionary.

Constraints

`packed` >= 0. `mapping` has at least 1 entry. Number of entries in mapping <= 1000. Bit positions can be large but within Python's integer range. Complexity: O(n) time where n is number of flags, O(n) space.

Example

>>> parse_flags(9, {'debug': 0, 'verbose': 3})
{'debug': True, 'verbose': True}
>>> parse_flags(0, {'a': 1, 'b': 0})
{'a': False, 'b': False}
>>> parse_flags(1, {'alpha': 0, 'beta': 2})
{'alpha': True, 'beta': False}
10 points ~12 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

To check if a bit at position i is set, use: (packed >> i) & 1.
Iterate over mapping.items() and build a new dictionary.
The result dictionary should have the same keys as mapping but with boolean values.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.