Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class InvertedIndex:
- def __init__(self):
- self.index = {}
- def add_document(self, doc_id, content):
- words = content.lower().split()
- for word in words:
- if word not in self.index:
- self.index[word] = set()
- self.index[word].add(doc_id)
- def search(self, query):
- query_words = query.lower().split()
- result = set.intersection(*[self.index.get(word, set()) for word in query_words])
- return list(result)
- # Usage
- index = InvertedIndex()
- index.add_document(1, "Java performance tuning techniques")
- index.add_document(2, "Optimizing JVM for high throughput")
- index.add_document(3, "Python vs Java: A performance comparison")
- print(index.search("java performance")) # Output: [1, 3]
Advertisement
Add Comment
Please, Sign In to add comment