medium +25 pts

Multiprocessing Queue

Use a multiprocessing queue to compute factorials in parallel and return combined results.

Write a function `parallel_factorials(numbers)` that takes a list of non-negative integers and returns a list of their factorials in the same order. The function must use exactly two processes to compute the factorials concurrently, communicating the results back to the parent process via a `multiprocessing.Queue`. Each process should handle approximately half of the numbers. The returned list must satisfy `result[i] == math.factorial(numbers[i])` for every index `i`. Your solution must: - Use `multiprocessing.Queue` to pass results from the child processes to the parent process. - Distribute the work evenly across two processes: the first process computes factorials for indices `0` to `len(numbers)//2 - 1` (or until the midpoint), the second process computes the rest. For an empty input, no work is needed. - Preserve the original order of numbers in the output. - Not reorder or modify the input list. Implement the function with signature `parallel_factorials(numbers)`. Do not use any external libraries or modules other than `math` and `multiprocessing`.

Constraints

- `0 <= len(numbers) <= 10000` - Each `numbers[i]` is a non-negative integer with `0 <= numbers[i] <= 20` (so factorial fits in a 64-bit integer? Actually 20! fits in 64-bit, but `math.factorial` handles any size, but we restrict to keep it simple). - The solution should be efficient enough to handle the maximum input size in under five seconds. - You must spawn exactly two processes. Do not use a pool.

Example

>>> parallel_factorials([])
[]
>>> parallel_factorials([0,1,2,3])
[1, 1, 2, 6]
>>> parallel_factorials([5,4])
[120, 24]
>>> parallel_factorials([1,0,5])
[1, 1, 120]
25 points ~25 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Split the list into two halves and pass each half to a separate Process.
In each process, compute factorials for its assigned numbers and put the (index, result) pairs into the shared Queue.
The parent process collects from the Queue and places results into a list at the correct index.
Don't forget to join the processes to ensure all results are collected.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.