ℹ️ Select 'Choose Exercise', or randomize 'Next Random Exercise' in selected language.

Choose Exercise:
Timer 00:00
WPM --
Score --
Acc --
Correct chars --

YAML Path Navigator

YAML

Goal -- WPM

Ready
Exercise Algorithm Area
1import yaml
2
3def get_nested_value(data, path):
4"""Retrieves a value from a nested YAML dictionary using a list of keys.
5
6Args:
7data (dict): The YAML data structure.
8path (list): A list of keys representing the path to the value.
9
10Returns:
11The value at the specified path, or None if the path is invalid.
12"""
13current_data = data
14for key in path:
15if not isinstance(current_data, dict):
16print(f"Error: Expected a dictionary at path segment '{key}', but found {type(current_data).__name__}.")
17return None
18if key not in current_data:
19print(f"Error: Key '{key}' not found in the current dictionary.")
20return None
21current_data = current_data[key]
22return current_data
23
24def process_yaml_config(config_string):
25"""Parses a YAML string and retrieves a specific configuration value.
26
27Args:
28config_string (str): A string containing YAML configuration.
29
30Returns:
31The value of the 'database.port' setting, or None if not found.
32"""
33try:
34config_data = yaml.safe_load(config_string)
35if not isinstance(config_data, dict):
36print("Error: Parsed YAML is not a dictionary.")
37return None
38
39db_path = ['database', 'port']
40db_port = get_nested_value(config_data, db_path)
41
42if db_port is not None:
43print(f"Database port found: {db_port}")
44else:
45print("Database port could not be retrieved.")
46
47return db_port
48
49except yaml.YAMLError as e:
50print(f"Error parsing YAML: {e}")
51return None
52except Exception as e:
53print(f"An unexpected error occurred: {e}")
54return None
55
56# Example Usage:
57if __name__ == "__main__":
58valid_yaml = """
59server:
60host: localhost
61port: 8080
62database:
63type: postgresql
64host: db.example.com
65port: 5432
66username: admin
67"""
68
69invalid_path_yaml = """
70server:
71host: localhost
72database:
73type: mysql
74host: db.example.com
75"""
76
77non_dict_yaml = "[1, 2, 3]"
78
79print("--- Testing valid YAML ---")
80process_yaml_config(valid_yaml)
81
82print("\n--- Testing YAML with invalid path ---")
83process_yaml_config(invalid_path_yaml)
84
85print("\n--- Testing non-dictionary YAML ---")
86process_yaml_config(non_dict_yaml)
87
88print("\n--- Testing empty YAML string ---")
89process_yaml_config("")
90
91print("\n--- Testing YAML with non-dict at intermediate path ---")
92intermediate_non_dict_yaml = """
93config:
94settings: 123
95database:
96port: 9000
97"""
98process_yaml_config(intermediate_non_dict_yaml)
Algorithm description viewbox

YAML Path Navigator

Algorithm description:

This algorithm parses a YAML string and navigates through its nested structure to retrieve a specific value using a predefined path. It's commonly used for reading configuration files, where settings are organized hierarchically. For instance, retrieving the database port from a server configuration file.

Algorithm explanation:

The `get_nested_value` function iterates through a list of keys, descending into a dictionary at each step. It includes checks to ensure that the current data structure is a dictionary and that the key exists before proceeding. If any check fails, it prints an error and returns `None`. The `process_yaml_config` function first uses `yaml.safe_load` to parse the input string, handling potential `yaml.YAMLError`. It then calls `get_nested_value` with a specific path ('database', 'port'). The time complexity for parsing YAML is typically O(N), where N is the number of characters in the string. The navigation part is O(P), where P is the length of the path. Space complexity is O(N) for storing the parsed YAML data. Edge cases handled include invalid YAML format, non-dictionary root, missing keys, and non-dictionary intermediate values.

Pseudocode:

Function get_nested_value(data, path):
  current_data = data
  For each key in path:
    If current_data is not a dictionary:
      Print error and return None
    If key is not in current_data:
      Print error and return None
    current_data = current_data[key]
  Return current_data

Function process_yaml_config(config_string):
  Try:
    config_data = parse YAML string config_string
    If config_data is not a dictionary:
      Print error and return None
    
    db_port = get_nested_value(config_data, ['database', 'port'])
    
    If db_port is not None:
      Print "Database port found: " + db_port
    Else:
      Print "Database port could not be retrieved."
    
    Return db_port
  Catch YAML parsing error:
    Print error and return None
  Catch any other error:
    Print error and return None