Advertisement
nathanwailes

TreeMaps / SortedDicts

Jun 9th, 2024 (edited)
525
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.45 KB | None | 0 0
  1. """
  2. A TreeMap is a self-balancing binary search tree. In modern languages, this is normally implemented as a Red-black tree.
  3.  
  4. TreeMap comes in handy when you need:
  5. 1. fast random access by key
  6. 2. maintaining order of the key, as well as
  7. 3. updating the key order quickly
  8.  
  9. If the requirements are only 1) and 2), we can get away with a hashmap and a list/array and that's exactly what most interview problems ask.
  10.  
  11. Python does not have a built-in TreeMap data structure as found in some other languages like Java. However, you can achieve similar functionality using the sortedcontainers module, specifically the SortedDict class. This module provides efficient implementations of sorted collections, including sorted dictionaries which can function similarly to a TreeMap.
  12.  
  13. A SortedDict is different from collections.OrderedDict in that a SortedDict maintains the keys in sorted order, while an OrderedDict maintains the keys in the order in which they were inserted (similar to a list that is repeatedly appended to).
  14. """
  15. from sortedcontainers import SortedDict
  16.  
  17. # Creating a SortedDict
  18. tree_map = SortedDict()
  19.  
  20. # Adding elements
  21. tree_map['b'] = 2
  22. tree_map['a'] = 1
  23. tree_map['c'] = 3
  24.  
  25. # Accessing elements
  26. print(tree_map['a'])  # Output: 1
  27. print(tree_map['b'])  # Output: 2
  28. print(tree_map['c'])  # Output: 3
  29.  
  30. # Checking for existence of keys
  31. print('a' in tree_map)  # Output: True
  32. print('d' in tree_map)  # Output: False
  33.  
  34. # Removing elements
  35. del tree_map['b']
  36.  
  37. # Iterating through the SortedDict
  38. for key in tree_map:
  39.     print(f"{key}: {tree_map[key]}")  # Output: a: 1, c: 3
  40.  
  41. # Getting all keys and values
  42. keys = tree_map.keys()
  43. values = tree_map.values()
  44. items = tree_map.items()
  45.  
  46. print("Keys:", list(keys))       # Output: ['a', 'c']
  47. print("Values:", list(values))   # Output: [1, 3]
  48. print("Items:", list(items))     # Output: [('a', 1), ('c', 3)]
  49.  
  50. # Finding the smallest and largest keys
  51. smallest_key = tree_map.peekitem(0)[0]  # Get the first item (smallest key)
  52. largest_key = tree_map.peekitem(-1)[0]  # Get the last item (largest key)
  53.  
  54. print("Smallest key:", smallest_key)  # Output: a
  55. print("Largest key:", largest_key)    # Output: c
  56.  
  57. # Finding the closest key greater than or equal to a given key
  58. key = tree_map.bisect_left('b')
  59. if key < len(tree_map):
  60.     print("Closest key >= 'b':", tree_map.peekitem(key)[0])  # Output: c
  61.  
  62. # Example usage
  63. print("TreeMap after all operations:", tree_map)  # Output: SortedDict({'a': 1, 'c': 3})
  64.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement