This question evaluates proficiency in string parsing and template substitution, efficient use of dictionaries for key lookups, and the ability to reason about algorithmic time and space complexity.
You are given:
values = {
"db_host": "example.com",
"db_port": 5001
}
{{
and
}}
, for example:
"application is now connecting to {{db_host}}:{{db_port}}"
Implement a function that replaces each placeholder in the template string with the corresponding value from the dictionary. For the example above, the output should be:
"application is now connecting to example.com:5001"
Assume:
Describe your approach and then implement the function in a programming language of your choice.
Now, instead of a single template string, you are given another dictionary where each value is a template string that may contain the same kind of {{key}} placeholders, and you are also given the same values dictionary used for substitution.
Example:
values = {
"db_host": "example.com",
"db_port": 5001
}
templates = {
"conn_msg": "application is now connecting to {{db_host}}:{{db_port}}",
"short_msg": "{{db_host}}:{{db_port}}"
}
Implement a function that takes values and templates and returns a new dictionary where each value in templates has had its placeholders replaced using values.
Explain your algorithm, including its time complexity in terms of:
L
= total length of all template strings
K
= number of distinct keys in the
values
dictionary.