We are back with a bang for this New Year! Let's continue daily and learn a Python and Java program continuously as planned!
Python for a day, Java for another, let's reach our target of 100 days of Coding successfully!
Happy New Year learners! Happy 2025!
Problem Statement
You are tasked with organizing and searching New Year's resolutions. Write a Python program that uses a Binary Search Tree (BST) to:
- Insert the given resolutions into the BST.
- Search for a specific resolution in the BST.
- Display all resolutions in lexicographical order.
The resolutions will be provided as a single string, with individual resolutions separated by the |
character.
Function Description
Complete the following functions:
insert(root, key)
- Inserts a resolution (key) into the BST rooted at
root
. - Returns the root of the updated BST.
- Inserts a resolution (key) into the BST rooted at
search(root, key)
- Searches for a specific resolution (key) in the BST rooted at
root
. - Returns
True
if the resolution exists, otherwise returnsFalse
.
- Searches for a specific resolution (key) in the BST rooted at
inorder(root)
- Performs an in-order traversal of the BST and returns a list of resolutions in lexicographical order.
main()
- Parses input, builds the BST, performs a search, and displays the results.
Input Format
- A single string containing resolutions separated by the
|
character.
Example:"Exercise more|Read more books|Learn Python|Save money|Travel the world|Be more organized"
- A single string specifying the resolution to search for.
Example:"Learn Python"
Output Format
- Print whether the searched resolution exists in the BST.
Format:"Searching for '<resolution>': Found!"
or"Searching for '<resolution>': Not found."
- Print all resolutions in sorted order under the title:
"New Year's Resolutions in Sorted Order:"
Each resolution should be prefixed with-
.
Sample Test Cases
Sample Input 1
Sample Output 1
Sample Input 2
Sample Output 2
Sample Input 3
Sample Output 3
Constraints
- The input string of resolutions will not be empty.
- Resolutions are case-sensitive.
- The number of resolutions (
n
) will not exceed 100.
Python Code
class Node:
def __init__(self, key):
self.key = key
self.left = None
self.right = None
class BST:
def __init__(self):
self.root = None
def insert(self, root, key):
if root is None:
return Node(key)
if key < root.key:
root.left = self.insert(root.left, key)
elif key > root.key:
root.right = self.insert(root.right, key)
return root
def search(self, root, key):
if root is None or root.key == key:
return root is not None
if key < root.key:
return self.search(root.left, key)
return self.search(root.right, key)
def inorder(self, root, result):
if root:
self.inorder(root.left, result)
result.append(root.key)
self.inorder(root.right, result)
return result
def main():
resolutions = input("Enter resolutions separated by '|': ").strip().split("|")
search_query = input("Enter the resolution to search for: ").strip()
bst = BST()
root = None
for resolution in resolutions:
root = bst.insert(root, resolution.strip())
found = bst.search(root, search_query)
print(f"Searching for '{search_query}':", "Found!" if found else "Not found.")
print("\nNew Year's Resolutions in Sorted Order:")
sorted_resolutions = bst.inorder(root, [])
for res in sorted_resolutions:
print("- " + res)
if __name__ == "__main__":
main()
Insights
- Modular Design: The code is well-structured with separate classes for
Node
andBST
and amain()
function for input handling and orchestration. - Efficient Data Structure: Uses a Binary Search Tree (BST) for storing resolutions, ensuring efficient operations like insertion and search.
- Insertion Logic: The
insert
method maintains BST properties and avoids duplicates naturally by design. - Search Method: Recursively checks for a resolution, providing
O(log n)
complexity for average cases. - In-Order Traversal: Returns resolutions in lexicographical order, leveraging the BST structure.
- Input Parsing: Parses resolutions from a single string using
|
as a delimiter, simplifying user input. - Output Formatting: Provides user-friendly messages for search results and outputs resolutions as a neatly formatted list.
- Case Sensitivity: Resolutions are treated as case-sensitive, differentiating between "Exercise" and "exercise."
- Edge Case Resilience: Handles empty trees gracefully and ignores duplicate resolutions during insertion.
- Scalability Concerns: Efficient for moderate input sizes but could degrade to
O(n)
in worst-case scenarios (e.g., unbalanced BST).
🎉 Wishing all our Learners a Happy New Year filled with curiosity and growth! 🚀 Embrace challenges, keep coding, and let each bug teach you something new—2025 is yours to conquer! 🌟
Comments
Post a Comment