Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python3
- # -*- coding: utf-8 -*-
- # Filename: treemap_sort_demo.py
- # Version: 1.0.0
- # Author: Jeoi Reqi
- """
- Description:
- - A TreeMap is a self-balancing binary search tree commonly implemented as a Red-black tree in modern programming languages.
- Key features of a TreeMap:
- 1. Enables efficient key-based access, ensuring quick retrieval of elements by their keys.
- 2. Maintains keys automatically in sorted order, facilitating easy sequential access.
- 3. Allows rapid updates to the sorted order of keys when elements are inserted or removed.
- Additional Notes:
- - For scenarios where fast key access and maintaining key order (points 1 and 2) are essential, simpler data structures like hashmaps or arrays suffice.
- - Although Python lacks a built-in TreeMap, the sortedcontainers module offers a similar solution with its SortedDict class.
- - SortedDict maintains keys in sorted order, unlike collections.OrderedDict, which retains insertion order.
- """
- from sortedcontainers import SortedDict
- # Creating a SortedDict
- tree_map = SortedDict()
- # Adding elements
- tree_map['b'] = 2
- tree_map['a'] = 1
- tree_map['c'] = 3
- # Accessing elements
- print("Accessing elements:\n")
- print("\tValue at key 'a':", tree_map['a']) # Output: 1
- print("\tValue at key 'b':", tree_map['b']) # Output: 2
- print("\tValue at key 'c':", tree_map['c']) # Output: 3
- # Checking for existence of keys
- print("\nChecking for existence of keys:\n")
- print("\tIs 'a' in TreeMap:", 'a' in tree_map) # Output: True
- print("\tIs 'd' in TreeMap:", 'd' in tree_map) # Output: False
- # Removing elements
- del tree_map['b']
- # Iterating through the SortedDict
- print("\nIterating through the SortedDict:\n")
- for key in tree_map:
- print(f"\t{key}: {tree_map[key]}") # Output: a: 1, c: 3
- # Getting all keys and values
- keys = tree_map.keys()
- values = tree_map.values()
- items = tree_map.items()
- print("\nResults:\n")
- print("\tAll Keys:", list(keys)) # Output: ['a', 'c']
- print("\tAll Values:", list(values)) # Output: [1, 3]
- print("\tAll Items:", list(items)) # Output: [('a', 1), ('c', 3)]
- # Finding the smallest and largest keys
- smallest_key = tree_map.peekitem(0)[0] # Get the first item (smallest key)
- largest_key = tree_map.peekitem(-1)[0] # Get the last item (largest key)
- print("\n\tSmallest key:", smallest_key) # Output: a
- print("\tLargest key:", largest_key) # Output: c
- # Finding the closest key greater than or equal to a given key
- key = tree_map.bisect_left('b')
- if key < len(tree_map):
- print("\tClosest key >= 'b':", tree_map.peekitem(key)[0]) # Output: c
- # Example usage
- print("\nTreeMap after all operations:\n\n ", tree_map) # Output: SortedDict({'a': 1, 'c': 3})
- print("\nSorting Complete!\n\n\tExiting Program... GoodBye!\n")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement