medium +15 pts

Bit Mask Permissions

Compose, combine, and check permission bit masks with bitwise operations.

Design a small utility for Unix-inspired permission masks. Permission bits are represented as integers using powers of two: READ = 4, WRITE = 2, EXECUTE = 1. Implement the following three functions in Python: 1. `compose_mask(permissions: list[str]) -> int` — takes a list of permission names (each exactly one of "READ", "WRITE", "EXECUTE") and returns the bit mask that has the corresponding bits set. Duplicate names are allowed but should not change the mask. An empty list returns 0. 2. `add_permission(mask: int, permission: str) -> int` — returns a new mask with the given permission's bit added (set to 1). The original mask must not be changed. 3. `has_permission(mask: int, permission: str) -> bool` — returns True if the given permission's bit is set in the mask, otherwise False. All arguments are valid: permission names are from the three constants, masks are non-negative integers. Example: if `perm_to_bit = {"READ": 4, "WRITE": 2, "EXECUTE": 1}`, then `compose_mask(["READ", "EXECUTE"])` returns 5, `add_permission(5, "WRITE")` returns 7, and `has_permission(7, "WRITE")` returns True.

Constraints

- Permission names are exactly 'READ', 'WRITE', 'EXECUTE' (case-sensitive) - Input masks are non-negative integers (0 <= mask <= 2^31-1) - The list passed to `compose_mask` may contain duplicates and can be empty - Your functions must not mutate any input lists or the original mask value (integers are immutable anyway)

Example

>>> compose_mask(["READ", "EXECUTE"])
5
>>> add_permission(5, "WRITE")
7
>>> has_permission(7, "WRITE")
True
>>> has_permission(5, "WRITE")
False
15 points ~20 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Use a dictionary to map permission names to their bit values, e.g., {'READ': 4, 'WRITE': 2, 'EXECUTE': 1}.
For `compose_mask`, accumulate the bitwise OR of the bit values of the names in the list.
For `add_permission`, use the bitwise OR operator to set a bit: `mask | bit`.
For `has_permission`, check if `(mask & bit) != 0`.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.