I am getting all the answers correct. But still the solution is not accepted as only 4/5 tests cases are passed.
I have not posted the whole problem statement but the problem is similar to this.
I want to know if there are any more optimizations possible.
import sys
class Queue(object):
input_array = []
def __init__(self, input_array=None):
if not input_array:
self.input_array = []
else:
self.input_array = input_array
def enqueue(self, element):
self.input_array.append(element)
def dequeue(self):
return self.input_array.pop(0)
def first(self):
return self.input_array[0]
def last(self):
return self.input_array[-1]
def size(self):
return len(self.input_array)
def get_queue(self):
return self.input_array
def get_queue_after_first(self):
return self.input_array[1:]
def __str__(self):
return "Current Queue: {0}".format(self.input_array)
def answer(document, searchTerms):
no_of_search_terms = 0
count = dict()
for searchTerm in searchTerms:
if searchTerm in count:
count[searchTerm] += 1
else:
no_of_search_terms += 1
count.update({searchTerm: 1})
q = Queue()
len_q = Queue()
smallest_snippet_size = sys.maxint
offsets = tuple()
tokens = document.split()
for position, token in enumerate(tokens, start=1):
if count.get(token, 0):
q.enqueue(token)
len_q.enqueue(position)
while q.first() in q.get_queue_after_first():
q.dequeue()
len_q.dequeue()
current_block_len = len_q.last() - len_q.first() + 1
if (q.size() >= no_of_search_terms) and (current_block_len < smallest_snippet_size):
smallest_snippet_size = current_block_len
offsets = (len_q.first() - 1, len_q.last())
return " ".join(tokens[offsets[0]: offsets[1]])
if __name__ == '__main__':
assert (answer("world there hello hello where world", ["hello", "world"]) == 'world there hello')
assert (answer("many google employees can program", ["google", "program"]) == 'google employees can program')
assert (answer("some tesla cars can autopilot", ["tesla", "autopilot"]) == 'tesla cars can autopilot')
assert (answer("a b c d a", ["c", "d", "a"]) == 'c d a')
assert (answer("the cats run very fast in the rain", ["cats", "run", "rain"]) == 'cats run very fast in the rain')
assert (answer("the cats run very fast in the rain run cats", ["cats", "run", "rain"]) == 'rain run cats')
assert (answer("hello", ["hello"]) == 'hello')