Nested Variable Expansion
MediumGraphs ยท Google
Given a dict variables mapping names to template strings and a string text, return text with every reference ${name} replaced by that variable's fully expanded value. A name is one or more letters, digits or underscores, and is case-sensitive. A reference to a name not in variables stays as written, and so does any other $ or brace that is not part of a reference.
Variable values are expanded by the same rules, to any depth, and the output is never scanned for references again. If expanding text reaches a variable that depends on itself, directly or through other variables, return "CYCLE".
Example 1
- Input:
- variables = {"host": "db-${env}", "env": "prod", "url": "https://${host}:${port}"}, text = "${url}/x"
- Output:
- "https://db-prod:${port}/x"
- Explanation
urlexpands throughhostandenv;portis not defined, so its reference stays.
Example 2
- Input:
- variables = {"a": "${b}${c}", "b": "${d}", "c": "${d}", "d": "1", "loop": "${loop}"}, text = "${a}"
- Output:
- "11"
- Explanation
dis reached twice, throughband throughc, which is not a cycle.loopis never reached.
Example 3
- Input:
- variables = {"a": "x${b}", "b": "${c}y", "c": "${a}"}, text = "go ${a}"
- Output:
- "CYCLE"
Constraints
0 <= len(variables) <= 10001 <= len(name) <= 20for every variable name, using only letters, digits and underscores0 <= len(variables[name]) <= 200and0 <= len(text) <= 1000- When there is no cycle, the expanded result has at most
100000characters