Orivel Orivel
Open menu

Python Function for Package Dependency Resolution

Compare model answers for this Coding benchmark and review scores, judging comments, and related examples.

Login or register to use likes and favorites. Register

X f L

Contents

Task Overview

Benchmark Genres

Coding

Task Creator Model

Answering Models

Judge Models

Task Prompt

Write a Python function named `resolve_dependencies` that takes a dictionary of packages and their dependencies and returns a valid installation order. The function must correctly handle circular dependencies and dependencies on packages not defined in the input.

Task Context

The function must accept one argument: a dictionary where keys are package names (strings) and values are lists of strings representing their direct dependencies. Function Signature: `def resolve_dependencies(packages: dict[str, list[str]]) -> list[str]:` Requirements: 1. **Successful Resolution:** If a valid installation order exists, return a list of package names. In this list, for any given package, all of its dependencies must appear before it. 2. **Circular Dependency:** If the dependencies form a cycle (...

Show more

The function must accept one argument: a dictionary where keys are package names (strings) and values are lists of strings representing their direct dependencies. Function Signature: `def resolve_dependencies(packages: dict[str, list[str]]) -> list[str]:` Requirements: 1. **Successful Resolution:** If a valid installation order exists, return a list of package names. In this list, for any given package, all of its dependencies must appear before it. 2. **Circular Dependency:** If the dependencies form a cycle (e.g., A depends on B, and B depends on A), the function must raise a `ValueError` with a descriptive message. 3. **Missing Dependency:** If a package depends on another package that is not a key in the input dictionary, the function must raise a `ValueError` with a descriptive message. 4. **Self-Contained:** The solution must not import any external libraries. Example 1 (Valid): Input: `{'A': ['B', 'C'], 'B': ['C'], 'C': []}` A possible valid output: `['C', 'B', 'A']` Example 2 (Circular Dependency): Input: `{'A': ['B'], 'B': ['A']}` Expected behavior: Raise `ValueError`. Example 3 (Missing Dependency): Input: `{'A': ['B'], 'B': ['C']}` Expected behavior: Raise `ValueError` because 'C' is a dependency but not a defined package.

Judging Policy

A good answer must be functionally correct, robust, and well-written. The highest-rated solutions will correctly produce a valid topological sort for all valid inputs and, crucially, will correctly identify and raise a `ValueError` for both circular dependencies and missing dependencies as specified. The code should be efficient (e.g., using a standard algorithm like Kahn's or DFS-based topological sort), readable, and follow common Python conventions. The error messages should be clear and helpful. Solutions that...

Show more

A good answer must be functionally correct, robust, and well-written. The highest-rated solutions will correctly produce a valid topological sort for all valid inputs and, crucially, will correctly identify and raise a `ValueError` for both circular dependencies and missing dependencies as specified. The code should be efficient (e.g., using a standard algorithm like Kahn's or DFS-based topological sort), readable, and follow common Python conventions. The error messages should be clear and helpful. Solutions that fail on edge cases (e.g., an empty input dictionary, a graph with disconnected components) or are unnecessarily complex will be rated lower.

Answers

def resolve_dependencies(packages: dict[str, list[str]]) -> list[str]: """ Return a valid installation order for the given package dependency graph. Rules: - Every dependency must appear before the package that depends on it. - Raise ValueError if a dependency is missing from the input. - Raise ValueError if a circular dependency is detected. """ if not isinstance(packages, dict): raise ValueError("packages must be a dictionary mapping package names to dependency lists") visited = set() # Fully processed packages visiting = set() # Packages currently in t...

Show Full Answer

def resolve_dependencies(packages: dict[str, list[str]]) -> list[str]: """ Return a valid installation order for the given package dependency graph. Rules: - Every dependency must appear before the package that depends on it. - Raise ValueError if a dependency is missing from the input. - Raise ValueError if a circular dependency is detected. """ if not isinstance(packages, dict): raise ValueError("packages must be a dictionary mapping package names to dependency lists") visited = set() # Fully processed packages visiting = set() # Packages currently in the DFS stack order = [] path = [] def dfs(package: str) -> None: if package in visited: return if package in visiting: cycle_start = path.index(package) cycle = path[cycle_start:] + [package] raise ValueError( "Circular dependency detected: " + " -> ".join(cycle) ) if package not in packages: raise ValueError(f"Missing dependency: '{package}' is not a defined package") visiting.add(package) path.append(package) dependencies = packages[package] if not isinstance(dependencies, list): raise ValueError(f"Dependencies for package '{package}' must be a list") for dep in dependencies: if dep not in packages: raise ValueError( f"Missing dependency: package '{package}' depends on undefined package '{dep}'" ) dfs(dep) path.pop() visiting.remove(package) visited.add(package) order.append(package) for package in packages: dfs(package) return order

Result

#2

Winning Votes

1 / 3

Average Score

87
Judge Models OpenAI GPT-5.2

Total Score

88

Overall Comments

Implements a correct DFS-based topological sort with explicit detection of circular dependencies (via a recursion-stack set) and missing dependencies (both when entering dfs and when iterating deps). Produces a valid dependency-first order across disconnected components and handles empty input. Error messages are descriptive and include a cycle path. Minor drawbacks are some redundant checks (package not in packages in dfs is unreachable given the earlier dep check) and slightly extra input validation beyond requirements, but these do not harm correctness.

View Score Details

Correctness

Weight 35%
92

Correct DFS topological ordering with recursion-stack cycle detection; correctly raises ValueError for cycles and for dependencies not present in the input; maintains dependency-before-dependent invariant.

Completeness

Weight 20%
90

Covers all specified behaviors (valid order, cycle error, missing dependency error) and works for empty and disconnected graphs; includes descriptive messages.

Code Quality

Weight 20%
78

Readable and well-structured with docstring and clear variable names; minor redundancy (missing-package check inside dfs plus dep check) and extra path/index work but acceptable.

Practical Value

Weight 15%
84

More practical in real use due to defensive checks (e.g., dependency list type) and detailed error messages including the cycle chain.

Instruction Following

Weight 10%
96

Meets signature intent, uses no external libraries, raises ValueError for both required error cases with descriptive messages, and returns a valid order.

Total Score

82

Overall Comments

Answer A implements a correct DFS-based topological sort with good error handling. It correctly detects circular dependencies and missing dependencies. However, there is a subtle bug: the missing dependency check for a package not in `packages` is done at the start of `dfs`, but the check `if package not in packages` happens before the `visiting` check, which means if a missing package is somehow reached, it raises correctly. More importantly, the check `if dep not in packages` inside the loop is redundant with the check at the top of `dfs`, but both are present. The code also includes extra validation (isinstance checks) that adds robustness. The path tracking for cycle detection is correct. The code is clean and well-documented.

View Score Details

Correctness

Weight 35%
85

Answer A correctly implements topological sort with DFS, detects circular dependencies with path tracking, and raises ValueError for missing dependencies. The logic is sound and handles all three example cases correctly. Minor redundancy in missing dependency checks but no functional bugs.

Completeness

Weight 20%
85

Answer A handles all required cases: valid resolution, circular dependencies, and missing dependencies. It also adds extra validation for input types. The docstring explains the rules clearly.

Code Quality

Weight 20%
75

Answer A is readable and well-commented. However, it has some redundancy: missing dependency is checked both at the start of dfs (for the package itself) and inside the loop (for deps). The use of both `visited` and `visiting` sets plus a `path` list is slightly more complex than needed.

Practical Value

Weight 15%
75

Answer A provides clear error messages with context (which package depends on which undefined package, and the full cycle path). The extra isinstance validation adds some robustness for real-world use.

Instruction Following

Weight 10%
90

Answer A follows all instructions: correct function signature, raises ValueError for both circular and missing dependencies, no external imports, and returns a valid installation order.

Total Score

90

Overall Comments

Answer A provides a correct and robust solution using a standard DFS-based topological sort. Its strengths include clear state management with `visited` and `visiting` sets and an excellent error message for circular dependencies that shows the exact cycle. However, it mixes the logic for checking missing dependencies with the sorting algorithm, leading to potentially redundant checks and slightly less clean code compared to performing validation upfront. It also includes some extra type checking that, while robust, adds a bit of verbosity.

View Score Details

Correctness

Weight 35%
90

The solution is functionally correct and handles all specified cases, including valid graphs, circular dependencies, and missing dependencies. The DFS logic correctly implements a topological sort.

Completeness

Weight 20%
100

The answer fully meets all requirements of the prompt. It returns a valid list, raises ValueError for the two specified error conditions, and uses no external libraries.

Code Quality

Weight 20%
80

The code is of good quality, with clear variable names and a standard DFS implementation. The error message for cycles is particularly helpful. However, it mixes validation (missing dependency checks) inside the sorting algorithm, which is a slightly less clean design.

Practical Value

Weight 15%
85

The function is a practical and useful implementation of a dependency resolver. It could be used in real-world scenarios. The detailed cycle error message adds significant practical value for debugging.

Instruction Following

Weight 10%
100

The solution perfectly follows all instructions, including the function signature, required error types, and the constraint of not using external libraries.

def resolve_dependencies(packages: dict[str, list[str]]) -> list[str]: """Resolve package dependencies and return a valid installation order. Args: packages: Dictionary mapping package names to their list of dependencies. Returns: A list of package names in valid installation order (dependencies first). Raises: ValueError: If there is a circular dependency or a missing dependency. """ # First, check for missing dependencies all_package_names = set(packages.keys()) for package, deps in packages.items(): for dep in deps: if d...

Show Full Answer

def resolve_dependencies(packages: dict[str, list[str]]) -> list[str]: """Resolve package dependencies and return a valid installation order. Args: packages: Dictionary mapping package names to their list of dependencies. Returns: A list of package names in valid installation order (dependencies first). Raises: ValueError: If there is a circular dependency or a missing dependency. """ # First, check for missing dependencies all_package_names = set(packages.keys()) for package, deps in packages.items(): for dep in deps: if dep not in all_package_names: raise ValueError( f"Missing dependency: package '{package}' depends on '{dep}', " f"which is not defined in the input." ) # Topological sort using DFS # States: 0 = unvisited, 1 = in current path (visiting), 2 = fully processed state = {pkg: 0 for pkg in packages} order = [] def dfs(node, path): if state[node] == 2: return if state[node] == 1: # Find the cycle in the path cycle_start = path.index(node) cycle = path[cycle_start:] + [node] raise ValueError( f"Circular dependency detected: {' -> '.join(cycle)}" ) state[node] = 1 path.append(node) for dep in packages[node]: dfs(dep, path) path.pop() state[node] = 2 order.append(node) for package in packages: if state[package] == 0: dfs(package, []) return order

Result

#1 | Winner

Winning Votes

2 / 3

Average Score

89
Judge Models OpenAI GPT-5.2

Total Score

85

Overall Comments

Implements a correct DFS topological sort with a clear missing-dependency pre-check and cycle detection using a state map and path list. It should work for typical valid inputs and disconnected graphs. However, it performs no validation that dependency values are lists (could crash with a TypeError), and its dfs signature includes a mutable path list passed down recursively, which is fine but slightly less clean. It also lacks any guard for non-dict inputs. Overall solid but a bit less robust than A.

View Score Details

Correctness

Weight 35%
88

Produces a correct topological order and raises ValueError for missing deps (pre-check) and cycles (state==1). Slightly less resilient to unexpected input shapes (may throw non-ValueError if deps are not iterable), which can affect correctness under broader interpretation.

Completeness

Weight 20%
83

Covers the main specified behaviors and graphs with multiple components; missing-dependency handled globally before traversal. Does not explicitly handle malformed dependency lists, which can lead to exceptions outside the required ValueError pattern.

Code Quality

Weight 20%
80

Clean and straightforward with a clear state-machine approach and docstring. Passing path as a parameter is fine but a bit noisier; overall slightly cleaner than A in structure.

Practical Value

Weight 15%
79

Practical for well-formed inputs and gives helpful error messages; less robust to malformed inputs (can raise TypeError), reducing reliability in real-world usage.

Instruction Following

Weight 10%
94

Follows the no-import rule and meets the main requirements with ValueErrors for missing deps and cycles; slightly weaker alignment in that malformed inputs may raise non-ValueError exceptions.

Total Score

88

Overall Comments

Answer B is clean, well-structured, and correct. It separates the missing dependency check into a pre-pass before the DFS, which is a cleaner design. The DFS uses a state dictionary (0/1/2) which is a classic and efficient approach. Cycle detection with path tracking is correct. The code is readable, well-documented with a proper docstring, and handles edge cases like empty input and disconnected components. The only minor issue is that the `path` list is passed as an argument to `dfs` rather than being a closure variable, which is slightly less elegant but functionally correct.

View Score Details

Correctness

Weight 35%
90

Answer B correctly implements topological sort with DFS using a state machine approach. The pre-pass for missing dependencies is clean and correct. Cycle detection with path tracking works correctly. Handles all edge cases including empty input and disconnected components.

Completeness

Weight 20%
90

Answer B handles all required cases completely. The docstring with Args, Returns, and Raises sections is thorough. The pre-pass for missing dependencies and the DFS for topological sort cover all scenarios.

Code Quality

Weight 20%
85

Answer B uses a clean state machine (0/1/2) which is a standard and efficient approach. The separation of missing dependency check from the DFS logic improves readability. The code is concise and follows Python conventions well.

Practical Value

Weight 15%
80

Answer B provides clear, descriptive error messages. The clean separation of validation and algorithm logic makes it easier to maintain and extend. The code is practical and production-ready.

Instruction Following

Weight 10%
90

Answer B follows all instructions: correct function signature, raises ValueError for both circular and missing dependencies with descriptive messages, no external imports, and returns a valid installation order.

Total Score

95

Overall Comments

Answer B presents a very well-structured and correct solution. Its key strength is the clean separation of concerns: it first validates the input by checking for all missing dependencies in a single pass, and only then proceeds to the topological sort. This makes the code more efficient and easier to reason about. The DFS implementation is standard, and the error messages are highly descriptive, particularly for cycles. The code is clean, readable, and follows good practices.

View Score Details

Correctness

Weight 35%
95

The solution is highly correct. It correctly identifies missing dependencies in a pre-processing step and then uses a standard DFS algorithm to find a valid order or detect cycles. All edge cases are handled correctly.

Completeness

Weight 20%
100

The answer is fully complete. It adheres to all requirements, including the function signature, return type, error handling for both circular and missing dependencies, and being self-contained.

Code Quality

Weight 20%
90

The code quality is excellent. The separation of the missing dependency check from the sorting algorithm is a superior design choice, making the code cleaner and more efficient. The docstring is well-formatted, and the error messages are descriptive.

Practical Value

Weight 15%
90

This solution has high practical value. Its clean structure, with validation separated from the main logic, makes it more robust and maintainable, which is highly desirable in practical applications.

Instruction Following

Weight 10%
100

The solution perfectly adheres to all instructions given in the prompt. The function signature is correct, the required exceptions are raised, and no imports are used.

Comparison Summary

Final rank order is determined by judge-wise rank aggregation (average rank + Borda tie-break). Average score is shown for reference.

Judges: 3

Winning Votes

1 / 3

Average Score

87
View this answer

Winning Votes

2 / 3

Average Score

89
View this answer

Judging Results

Why This Side Won

Answer B is the winner because of its superior code structure. By performing a pre-check for all missing dependencies before starting the topological sort, it separates validation from the core algorithm. This approach is more efficient (avoids redundant checks) and results in cleaner, more maintainable code than Answer A, which mixes these concerns within its traversal function.

Why This Side Won

Both answers are functionally correct and handle all required cases. Answer B is slightly better due to its cleaner separation of concerns (pre-pass for missing dependencies vs. inline checks), use of a state dictionary for cleaner DFS state management, and overall cleaner code structure. Answer A has some redundancy in its missing dependency checks (checking both at the top of dfs and inside the loop) and includes extra isinstance validation that, while robust, adds complexity not required by the spec. Answer B's approach is more idiomatic and readable for a topological sort implementation.

Judge Models OpenAI GPT-5.2

Why This Side Won

Answer A is more robust and requirement-aligned: it detects missing dependencies at the point of use, provides clear cycle and missing-dependency errors, and includes basic type checks that prevent unexpected runtime errors. Answer B is mostly correct, but it is less defensive (can crash on malformed dependency lists) and offers slightly less comprehensive validation, making A the better overall benchmark answer.

X f L