Advertisement
Python253

treemap_sort_demo

Jun 24th, 2024 (edited)
396
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.79 KB | None | 0 0
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. # Filename: treemap_sort_demo.py
  4. # Version: 1.0.0
  5. # Author: Jeoi Reqi
  6.  
  7. """
  8. Description:
  9.    - A TreeMap is a self-balancing binary search tree commonly implemented as a Red-black tree in modern programming languages.
  10.  
  11. Key features of a TreeMap:
  12.    1. Enables efficient key-based access, ensuring quick retrieval of elements by their keys.
  13.    2. Maintains keys automatically in sorted order, facilitating easy sequential access.
  14.    3. Allows rapid updates to the sorted order of keys when elements are inserted or removed.
  15.  
  16. Additional Notes:
  17.    - For scenarios where fast key access and maintaining key order (points 1 and 2) are essential, simpler data structures like hashmaps or arrays suffice.
  18.    - Although Python lacks a built-in TreeMap, the sortedcontainers module offers a similar solution with its SortedDict class.
  19.    - SortedDict maintains keys in sorted order, unlike collections.OrderedDict, which retains insertion order.
  20. """
  21.  
  22. from sortedcontainers import SortedDict
  23.  
  24. # Creating a SortedDict
  25. tree_map = SortedDict()
  26.  
  27. # Adding elements
  28. tree_map['b'] = 2
  29. tree_map['a'] = 1
  30. tree_map['c'] = 3
  31.  
  32. # Accessing elements
  33. print("Accessing elements:\n")
  34. print("\tValue at key 'a':", tree_map['a'])  # Output: 1
  35. print("\tValue at key 'b':", tree_map['b'])  # Output: 2
  36. print("\tValue at key 'c':", tree_map['c'])  # Output: 3
  37.  
  38. # Checking for existence of keys
  39. print("\nChecking for existence of keys:\n")
  40. print("\tIs 'a' in TreeMap:", 'a' in tree_map)  # Output: True
  41. print("\tIs 'd' in TreeMap:", 'd' in tree_map)  # Output: False
  42.  
  43. # Removing elements
  44. del tree_map['b']
  45.  
  46. # Iterating through the SortedDict
  47. print("\nIterating through the SortedDict:\n")
  48. for key in tree_map:
  49.     print(f"\t{key}: {tree_map[key]}")  # Output: a: 1, c: 3
  50.  
  51. # Getting all keys and values
  52. keys = tree_map.keys()
  53. values = tree_map.values()
  54. items = tree_map.items()
  55.  
  56. print("\nResults:\n")
  57. print("\tAll Keys:", list(keys))       # Output: ['a', 'c']
  58. print("\tAll Values:", list(values))   # Output: [1, 3]
  59. print("\tAll Items:", list(items))     # Output: [('a', 1), ('c', 3)]
  60.  
  61. # Finding the smallest and largest keys
  62. smallest_key = tree_map.peekitem(0)[0]  # Get the first item (smallest key)
  63. largest_key = tree_map.peekitem(-1)[0]  # Get the last item (largest key)
  64.  
  65. print("\n\tSmallest key:", smallest_key)  # Output: a
  66. print("\tLargest key:", largest_key)    # Output: c
  67.  
  68. # Finding the closest key greater than or equal to a given key
  69. key = tree_map.bisect_left('b')
  70. if key < len(tree_map):
  71.     print("\tClosest key >= 'b':", tree_map.peekitem(key)[0])  # Output: c
  72.  
  73. # Example usage
  74. print("\nTreeMap after all operations:\n\n       ", tree_map)  # Output: SortedDict({'a': 1, 'c': 3})
  75.  
  76. print("\nSorting Complete!\n\n\tExiting Program...   GoodBye!\n")
  77.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement