Orivel Orivel
Open menu

Implement a Dependency Resolver in Python

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

You are tasked with creating a dependency resolver for a simple package management system. Write a Python function `resolve_dependencies(package_definitions, target_package)` that determines the correct installation order for a given package and its dependencies. The `package_definitions` argument is a list of strings. Each string defines a package and its direct dependencies in the format: `'PackageName: Dep1, Dep2, ...'`. If a package has no dependencies, the format is `'PackageName:'`. Your function should: 1....

Show more

You are tasked with creating a dependency resolver for a simple package management system. Write a Python function `resolve_dependencies(package_definitions, target_package)` that determines the correct installation order for a given package and its dependencies. The `package_definitions` argument is a list of strings. Each string defines a package and its direct dependencies in the format: `'PackageName: Dep1, Dep2, ...'`. If a package has no dependencies, the format is `'PackageName:'`. Your function should: 1. Parse the input strings to build a dependency graph. 2. Given a `target_package`, find all its dependencies (including transitive ones). 3. Return a single list of strings representing the installation order. This list must be topologically sorted (a dependency must always appear before the package that depends on it). The `target_package` itself should be the last item in the list. The list should not contain duplicates. 4. Detect circular dependencies. If a cycle is found, raise a `ValueError` with a message that clearly indicates the cycle (e.g., 'Circular dependency detected involving: A -> B -> A'). 5. Detect missing packages. If a package lists a dependency that is not defined in `package_definitions`, raise a `ValueError` with a message like 'Missing package definition for: C'.

Task Context

Here is an example of valid input and expected output: `package_definitions = [` ` 'A: B, C',` ` 'B: D',` ` 'C: D, E',` ` 'D:',` ` 'E:'` `]` `target_package = 'A'` Expected output for `resolve_dependencies(package_definitions, 'A')`: `['D', 'E', 'B', 'C', 'A']` or `['E', 'D', 'B', 'C', 'A']` or `['D', 'E', 'C', 'B', 'A']` (any valid topological sort is acceptable). Example of an input that should raise a `ValueError` for a circular dependency: `package_definitions = ['A: B', 'B: A']` `target_package = 'A'`...

Show more

Here is an example of valid input and expected output: `package_definitions = [` ` 'A: B, C',` ` 'B: D',` ` 'C: D, E',` ` 'D:',` ` 'E:'` `]` `target_package = 'A'` Expected output for `resolve_dependencies(package_definitions, 'A')`: `['D', 'E', 'B', 'C', 'A']` or `['E', 'D', 'B', 'C', 'A']` or `['D', 'E', 'C', 'B', 'A']` (any valid topological sort is acceptable). Example of an input that should raise a `ValueError` for a circular dependency: `package_definitions = ['A: B', 'B: A']` `target_package = 'A'` Example of an input that should raise a `ValueError` for a missing package: `package_definitions = ['A: B', 'B: C']` (C is not defined) `target_package = 'A'`

Judging Policy

A correct solution must be a runnable Python function or class that adheres to the specified interface. The solution will be judged on several criteria: 1. **Correctness:** It must produce a valid, topologically sorted list of dependencies for all valid inputs. The order of dependencies at the same level (e.g., B and C in the example) does not matter. 2. **Error Handling:** It must correctly detect and raise `ValueError` with descriptive messages for both circular dependencies and missing package definitions. 3. **...

Show more

A correct solution must be a runnable Python function or class that adheres to the specified interface. The solution will be judged on several criteria: 1. **Correctness:** It must produce a valid, topologically sorted list of dependencies for all valid inputs. The order of dependencies at the same level (e.g., B and C in the example) does not matter. 2. **Error Handling:** It must correctly detect and raise `ValueError` with descriptive messages for both circular dependencies and missing package definitions. 3. **Robustness:** The code should correctly parse the input format and handle edge cases like packages with no dependencies, diamond dependencies, and self-dependencies. 4. **Code Quality:** The solution should be well-structured, readable, and reasonably efficient. The use of a standard graph traversal algorithm (like a Depth-First Search-based approach or Kahn's algorithm) is expected. The implementation should not be overly complex.

Answers

def resolve_dependencies(package_definitions, target_package): # Parse package definitions graph = {} for definition in package_definitions: if ':' not in definition: raise ValueError(f'Invalid package definition: {definition}') name, _, deps_str = definition.partition(':') name = name.strip() deps_str = deps_str.strip() if deps_str: deps = [d.strip() for d in deps_str.split(',')] else: deps = [] graph[name] = deps # Check for missing packages for pkg, deps in graph.items(): for dep in deps:...

Show Full Answer

def resolve_dependencies(package_definitions, target_package): # Parse package definitions graph = {} for definition in package_definitions: if ':' not in definition: raise ValueError(f'Invalid package definition: {definition}') name, _, deps_str = definition.partition(':') name = name.strip() deps_str = deps_str.strip() if deps_str: deps = [d.strip() for d in deps_str.split(',')] else: deps = [] graph[name] = deps # Check for missing packages for pkg, deps in graph.items(): for dep in deps: if dep not in graph: raise ValueError(f'Missing package definition for: {dep}') if target_package not in graph: raise ValueError(f'Missing package definition for: {target_package}') # Topological sort using DFS, only for packages reachable from target_package # States: 0 = unvisited, 1 = in progress, 2 = done state = {} result = [] path = [] # track current path for cycle detection def dfs(pkg): if state.get(pkg) == 2: return if state.get(pkg) == 1: # Find cycle in path cycle_start = path.index(pkg) cycle = path[cycle_start:] + [pkg] raise ValueError(f'Circular dependency detected involving: {" -> ".join(cycle)}') state[pkg] = 1 path.append(pkg) for dep in graph[pkg]: dfs(dep) path.pop() state[pkg] = 2 result.append(pkg) dfs(target_package) return result

Result

#2

Winning Votes

0 / 3

Average Score

75

Total Score

79

Overall Comments

Answer A provides a correct and functional dependency resolver using a standard DFS approach. It correctly handles circular dependencies and missing packages with the specified error messages. However, its input parsing is less robust, particularly regarding duplicate package definitions (which it overwrites) and malformed dependency lists (e.g., 'A: , B' would result in an empty string dependency).

View Score Details

Correctness

Weight 35%
88

The solution correctly performs topological sorting and raises appropriate errors for circular and missing dependencies. However, its parsing of dependency strings like 'A: , B' would incorrectly include an empty string as a dependency, which is a minor correctness flaw in graph construction.

Completeness

Weight 20%
70

The solution implements all core features but lacks handling for duplicate package definitions (it overwrites them) and is less robust in parsing malformed dependency strings, which reduces its completeness for real-world inputs.

Code Quality

Weight 20%
78

The code is readable and uses a standard DFS algorithm. The parsing logic is integrated directly into the main function. It is reasonably efficient and not overly complex.

Practical Value

Weight 15%
70

The solution is functional but less robust to common real-world input variations, such as duplicate package definitions or slightly malformed dependency lists, which limits its practical applicability without further refinement.

Instruction Following

Weight 10%
85

The solution adheres to the function signature, return type, error types, and specified error message formats. It correctly implements the core requirements.

Judge Models OpenAI GPT-5.2

Total Score

72

Overall Comments

Implements a correct DFS-based topological sort restricted to the target’s reachable subgraph, with cycle detection via an explicit path stack and clear cycle reporting. It correctly checks for missing package definitions (including missing target) before traversal. Weaknesses: parsing is a bit loose (doesn’t filter empty dependency tokens like 'A: B,', so it may raise a missing-package error for an empty string); it silently overwrites duplicate package definitions rather than rejecting them; and it does a global missing-dependency scan over all packages rather than just the reachable subset (not incorrect, but potentially surprising).

View Score Details

Correctness

Weight 35%
75

Correct DFS topological ordering for the target subgraph; cycle detection and missing-package detection generally work. However, trailing commas can produce an empty dependency name that triggers a misleading missing-package error, reducing correctness on loosely formatted inputs.

Completeness

Weight 20%
70

Meets core requirements (parse, topo sort, cycle/missing errors). Lacks handling of duplicate definitions and doesn’t sanitize empty dep tokens, which are common minor format issues.

Code Quality

Weight 20%
65

Readable and short; uses standard DFS states. Minor issues: path.index lookup inside cycle case and silent overwriting on duplicates; less defensive parsing.

Practical Value

Weight 15%
65

Useful as-is for clean inputs, but less resilient to slightly messy definitions and duplicates, which reduces real-world usefulness.

Instruction Following

Weight 10%
85

Implements the requested function and raises ValueError with descriptive messages including a cycle path; returns the correct format.

Total Score

74

Overall Comments

Answer A provides a correct and clean implementation of the dependency resolver. It properly parses input, detects missing packages, detects circular dependencies with path tracking, and performs DFS-based topological sort. The code is concise and readable. However, it lacks some edge case handling such as duplicate package definitions, empty package names, and non-string inputs. It also lacks a docstring and example usage.

View Score Details

Correctness

Weight 35%
85

Answer A correctly implements topological sort via DFS, properly detects circular dependencies with accurate cycle path reporting, detects missing packages, and produces valid installation orders. The core algorithm is correct for all specified test cases.

Completeness

Weight 20%
65

Answer A handles the main requirements: parsing, topological sort, cycle detection, and missing package detection. However, it does not handle edge cases like duplicate package definitions, empty package names, non-string inputs, or empty strings resulting from splitting dependencies.

Code Quality

Weight 20%
70

Answer A is concise and readable with clear variable names and comments. The code structure is straightforward. However, it lacks a docstring and the parsing logic is inline rather than separated into a helper function.

Practical Value

Weight 15%
65

Answer A is functional and would work in practice for well-formed inputs. However, the lack of input validation for edge cases reduces its robustness in real-world scenarios where inputs may be malformed.

Instruction Following

Weight 10%
75

Answer A follows the instructions well: it implements the required function signature, parses the input format, performs topological sort, detects cycles with descriptive messages, and detects missing packages. The error message format matches the examples.

def resolve_dependencies(package_definitions, target_package): """ Resolve dependencies for target_package and return a valid installation order. Args: package_definitions: list[str], each in the form 'Package: Dep1, Dep2' or 'Package:' target_package: str Returns: list[str]: topologically sorted installation order ending with target_package Raises: ValueError: on malformed input, missing package definitions, or circular dependencies """ def parse_definitions(definitions): graph = {} for entry in definitions: if not isins...

Show Full Answer

def resolve_dependencies(package_definitions, target_package): """ Resolve dependencies for target_package and return a valid installation order. Args: package_definitions: list[str], each in the form 'Package: Dep1, Dep2' or 'Package:' target_package: str Returns: list[str]: topologically sorted installation order ending with target_package Raises: ValueError: on malformed input, missing package definitions, or circular dependencies """ def parse_definitions(definitions): graph = {} for entry in definitions: if not isinstance(entry, str): raise ValueError(f"Invalid package definition: {entry}") if ':' not in entry: raise ValueError(f"Invalid package definition: {entry}") package, deps_part = entry.split(':', 1) package = package.strip() if not package: raise ValueError(f"Invalid package definition: {entry}") deps_part = deps_part.strip() if deps_part: deps = [dep.strip() for dep in deps_part.split(',') if dep.strip()] else: deps = [] if package in graph: raise ValueError(f"Duplicate package definition for: {package}") graph[package] = deps return graph graph = parse_definitions(package_definitions) if target_package not in graph: raise ValueError(f"Missing package definition for: {target_package}") order = [] state = {} # 0/unset = unvisited, 1 = visiting, 2 = visited stack = [] def dfs(package): if package not in graph: raise ValueError(f"Missing package definition for: {package}") package_state = state.get(package, 0) if package_state == 1: try: start = stack.index(package) cycle_path = stack[start:] + [package] except ValueError: cycle_path = [package, package] raise ValueError( "Circular dependency detected involving: " + " -> ".join(cycle_path) ) if package_state == 2: return state[package] = 1 stack.append(package) for dep in graph[package]: if dep not in graph: raise ValueError(f"Missing package definition for: {dep}") dfs(dep) stack.pop() state[package] = 2 order.append(package) dfs(target_package) return order # Example usage: if __name__ == "__main__": package_definitions = [ 'A: B, C', 'B: D', 'C: D, E', 'D:', 'E:' ] print(resolve_dependencies(package_definitions, 'A')) # Cycle example: # print(resolve_dependencies(['A: B', 'B: A'], 'A')) # Missing package example: # print(resolve_dependencies(['A: B', 'B: C'], 'A'))

Result

#1 | Winner

Winning Votes

3 / 3

Average Score

83

Total Score

86

Overall Comments

Answer B is a highly robust and well-structured solution. It excels in input parsing, handling duplicate package definitions and various malformed dependency list scenarios gracefully. It correctly implements the topological sort, detects circular dependencies, and identifies missing packages with accurate error messages. The use of a helper function for parsing improves modularity. A minor logical oddity exists in the cycle detection's `try-except` block, but it does not impact the correctness of the solution.

View Score Details

Correctness

Weight 35%
90

The solution correctly performs topological sorting and raises appropriate errors. It handles various parsing edge cases correctly, such as 'A: , B' not creating an empty string dependency. The cycle detection logic is sound, despite a minor, non-impacting logical oddity in the `try-except` block.

Completeness

Weight 20%
85

The solution is very complete, implementing all required features including robust parsing, graph building, topological sort, and comprehensive error handling. It correctly addresses duplicate package definitions and various malformed input scenarios.

Code Quality

Weight 20%
82

The code quality is strong, with good modularity achieved by separating parsing into a helper function. It includes a helpful docstring and uses a standard DFS. The `try-except` block in cycle detection is a minor logical oddity but doesn't significantly detract from overall quality.

Practical Value

Weight 15%
80

The solution offers high practical value due to its robust parsing and comprehensive error handling, including detection of duplicate package definitions. This makes it more resilient and reliable for use in a package management system.

Instruction Following

Weight 10%
90

The solution meticulously follows all explicit instructions, including function signature, return type, error types, and exact error message formats. It also goes beyond the explicit requirements by providing more robust input parsing, aligning well with the spirit of the task's robustness criterion.

Judge Models OpenAI GPT-5.2

Total Score

83

Overall Comments

Provides a robust, runnable DFS-based resolver with good parsing validation (non-string entries, missing ':', empty package name, trims deps and filters out empty tokens) and rejects duplicate package definitions. It correctly detects missing packages both for the target and any dependency encountered, and reports cycles with an explicit path trace. Code is well-structured and documented; included example usage is harmless though slightly extra for a benchmark answer.

View Score Details

Correctness

Weight 35%
85

Produces valid topological order ending with the target, no duplicates, correct handling of transitive deps, self-deps, and diamonds. Cycle and missing-package detection are correct and consistent during traversal.

Completeness

Weight 20%
85

Covers all specified requirements and adds sensible extras (duplicate definition detection, stronger malformed-input checks) without breaking the interface.

Code Quality

Weight 20%
80

Well-structured with helper parsing function, docstring, clear variable naming, and defensive checks. Cycle construction is clear; overall maintainable.

Practical Value

Weight 15%
80

More production-friendly due to validation, duplicate detection, and sanitizing dependency tokens; example usage helps quick verification.

Instruction Following

Weight 10%
80

Implements the requested function and error messages; includes extra example main block (not requested) but does not interfere with function behavior.

Total Score

81

Overall Comments

Answer B provides a correct and more robust implementation of the dependency resolver. It includes additional validation such as duplicate package detection, empty package name detection, non-string input validation, and filtering empty dependency strings from split results. It has a comprehensive docstring, well-structured code with a separate parse function, and includes example usage. The code handles more edge cases while maintaining readability.

View Score Details

Correctness

Weight 35%
85

Answer B correctly implements topological sort via DFS, properly detects circular dependencies with accurate cycle path reporting, detects missing packages, and produces valid installation orders. The core algorithm is correct for all specified test cases. The missing package check is done both upfront and during DFS traversal, which is slightly redundant but not incorrect.

Completeness

Weight 20%
80

Answer B handles all main requirements plus additional edge cases: duplicate package definitions, empty package names, non-string input validation, and filtering empty dependency strings. It also includes a docstring documenting the interface, arguments, return value, and exceptions.

Code Quality

Weight 20%
80

Answer B has better code organization with a separate parse_definitions helper function, a comprehensive docstring, clear variable names, and inline comments. The separation of concerns makes the code more maintainable and testable.

Practical Value

Weight 15%
75

Answer B is more practical due to its additional input validation, better error messages, and example usage in the __main__ block. The duplicate detection and input type checking make it more suitable for integration into a real package management system.

Instruction Following

Weight 10%
80

Answer B follows all instructions and goes slightly beyond by providing a docstring, example usage, and additional validation. The function signature matches exactly, error messages are descriptive and match the required format, and the topological sort is correctly implemented.

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

0 / 3

Average Score

75
View this answer

Winning Votes

3 / 3

Average Score

83
View this answer

Judging Results

Why This Side Won

Answer B wins because it handles more edge cases (duplicate packages, empty package names, non-string inputs, empty dependency strings after splitting), has better code organization with a separate parse function, includes a comprehensive docstring, and provides example usage. Both answers are correct for the core functionality, but Answer B is more robust and has higher code quality. The additional validation in Answer B makes it more suitable for real-world use.

Judge Models OpenAI GPT-5.2

Why This Side Won

Answer B wins due to stronger robustness and input validation while still meeting all functional requirements: it handles edge cases like trailing commas/empty dependency tokens, detects duplicate package definitions, and keeps clear cycle/missing-package errors. Answer A is largely correct but can mis-handle malformed dependency lists (e.g., introducing empty dependency names) and overwrites duplicates silently.

Why This Side Won

Answer B is superior due to its significantly more robust input parsing and handling of edge cases like duplicate package definitions and malformed dependency strings. While both answers correctly implement the core dependency resolution logic and error handling, B's enhanced robustness makes it more practical and complete for a real-world scenario.

X f L