Modules and imports · 16 / 16 Exercise Hard

Import order

Objective

When a module imports another one, the second must be loaded first. If two modules import each other, there is a circular import, which causes errors. Compute the load order or detect the cycle.

Instructions

  • Read n and then n lines with the format module dep1 dep2 ... (a module may have no dependencies). Every dependency is also one of the n modules.
  • Go through the modules in alphabetical order with a depth-first search (DFS), visiting their dependencies also in alphabetical order, and load each module after its dependencies.
  • If there is a cycle, show Circular import: a -> b -> a with the path, which starts and ends at the same module, as soon as you find it.
  • Otherwise show Load order: m1 m2 ... with the modules in the order in which they are loaded.
Input
4
app util config
util config
config
extra
Output
Load order: config util app extra

Open the editor in full screen: the statement on the left and your code, the output and the tests on the right.

Start exercise