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

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

YAML Sequence Reverser

YAML

Goal -- WPM

Ready
Exercise Algorithm Area
1import yaml
2
3def reverse_yaml_sequence(yaml_string):
4"""Reverses the order of elements in a top-level YAML sequence.
5
6Args:
7yaml_string (str): A string containing a YAML sequence.
8
9Returns:
10str: A string representing the reversed YAML sequence, or None if input is invalid.
11"""
12try:
13data = yaml.safe_load(yaml_string)
14
15if data is None:
16return "[]" # Return empty list for empty input
17
18if not isinstance(data, list):
19print("Error: Input YAML is not a sequence.")
20return None
21
22# Reverse the list in-place
23data.reverse()
24
25return yaml.dump(data, default_flow_style=False)
26
27except yaml.YAMLError as e:
28print(f"Error parsing YAML: {e}")
29return None
30except Exception as e:
31print(f"An unexpected error occurred: {e}")
32return None
33
34# Example Usage:
35if __name__ == "__main__":
36sequence_yaml = """
37- apple
38- banana
39- cherry
40"""
41
42empty_sequence_yaml = "[]"
43
44not_a_sequence_yaml = "key: value"
45
46print("--- Reversing a sequence ---")
47reversed_seq = reverse_yaml_sequence(sequence_yaml)
48if reversed_seq:
49print(reversed_seq)
50
51print("\n--- Reversing an empty sequence ---")
52reversed_empty = reverse_yaml_sequence(empty_sequence_yaml)
53if reversed_empty:
54print(reversed_empty)
55
56print("\n--- Attempting to reverse non-sequence ---")
57reversed_non_seq = reverse_yaml_sequence(not_a_sequence_yaml)
58if reversed_non_seq:
59print(reversed_non_seq)
60
61print("\n--- Reversing an empty string input ---")
62reversed_empty_str = reverse_yaml_sequence("")
63if reversed_empty_str:
64print(reversed_empty_str)
Algorithm description viewbox

YAML Sequence Reverser

Algorithm description:

This algorithm takes a YAML string representing a sequence (list) and reverses the order of its elements. It's a straightforward operation often used for processing ordered data where the sequence needs to be processed in reverse. For example, reversing a list of log entries to view the most recent ones first.

Algorithm explanation:

The `reverse_yaml_sequence` function first parses the input YAML string using `yaml.safe_load`. It checks if the parsed data is `None` (indicating an empty input) and returns an empty list string `[]` in that case. It then verifies that the parsed data is indeed a list; if not, it prints an error and returns `None`. If it's a valid list, the `data.reverse()` method is called to reverse the list in-place. Finally, `yaml.dump` is used to convert the reversed list back into a YAML string. The time complexity for parsing and dumping YAML is O(N), where N is the number of characters in the YAML string. The list reversal is O(L), where L is the number of elements in the list. Space complexity is O(N) for storing the parsed and dumped YAML. Edge cases handled include empty input strings, empty YAML sequences, and input that is not a YAML sequence.

Pseudocode:

Function reverse_yaml_sequence(yaml_string):
  Try:
    data = parse YAML yaml_string

    If data is None:
      Return "[]"

    If data is not a list:
      Print error and return None

    Reverse data in-place

    Return dump data as YAML string
  Catch YAML parsing error:
    Print error and return None
  Catch other errors:
    Print error and return None