Google Foobar Challenge: Spy Snippets in Python

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') 


Class attribute

Having input_array = [] defined at class level does not add anything except confusion.


I think that this:

no_of_search_terms = 0
count = dict()
for searchTerm in searchTerms:
    if searchTerm in count:
        count[searchTerm] += 1
        no_of_search_terms += 1
        count.update({searchTerm: 1})

could be done in a clearer and more efficient way using: collections.Counter.

Category: python Time: 2016-07-30 Views: 6

Related post

  • Why are scripts injected through innerHTML not executed whilst onerror and other on event attributes on elements are? - Google XSS Challenge 2 2014-06-12

    SPOILER ALERT : Do not continue if you do not want to be spoiled I am currently doing the Google XSS Challenge Level 2 . I am injecting XSS code that is inserted into the document using element.innerHTML. I don't understand why <script>alert("F

  • Why is google recaptcha challenge so long? 2015-08-02

    Google recaptcha challenge (which is submitted with text on image to google servers) looks like this: 03AHJ_VuuXgRZuuvh2gSOXYt0pTFa57RyNjwc_YHHxy6ksHp9nNA6dyyEMoxovo5eI0dHCHwjecE_e-xRtQy-LGqt3th1ALnvs0qeNS2DBH_6ATfk207p_ga0QkGsOSsjrkeIEuFerMpqC6Z_9Wi

  • Does Google also show rich snippets for small sites? 2010-09-19

    So far, I've seen rich snippets in Google search results only for large sites with a high number of elements (people, events, recipes, etc.). Does anyone know of an example where rich snippets are displayed for a small site with only a handful/a few

  • GCM (Google Cloud Messaging) push notification from python app server to iOS app 2016-01-28

    I'm trying to send push notifications to my iOS app with GCM. I tried to follow the (Google GCM) and (GCMServerDemo) for my app but I only can receive the notification printed on the xcode output: [body: hello, it's me, sound: default, collapse_key:

  • Google Analytics api sample code with python 2016-02-03

    I am a beginner using google's tutorial to learning to use google analytics api. I completely followed the tutorial but When I run this sample code from google,

  • How to generate Google Chart for data stored inside python collection? 2016-02-10

    I have written a simple web scrapper in python. It gathers some information and then prints it in the console. Now I would like to display the result in a more appealing way - a chart. I know Google Charts is a powerful tool and I'm determined to use

  • How to install insync-beta-xfce, the Google Drive client for Xfce (thunarx-python missing)? 2013-03-26

    There are different types of Insync available for Ubuntu (see here). I am trying to use it under Xfce, so the first choice would be to install the Xfce version. But I get this error: How to solve this? Installing the generic version works, but it als

  • using google api for speech recognition in python - activate on keyword 2016-01-31

    I am using the speech_recognition api for (yet another) home automation project and was wondering how to approach the issue of continuously listening. I would imagine it is not very practical to just have the api listening in a constant while loop, o

  • Rosetta Stone Code Golf Challenge: Print Certain Numbers; all snippets must be same length 2015-02-23

    Rosetta Stone Code Challenges are challenges where you must complete the task in as many languages as possible. The Challenge You will be given two numbers, n and s, in a list as input. The n will be a number you have to count up to. n will be any nu

  • Why does Google sometimes show fewer than the standard pair of lines for the "snippet"? 2010-09-17

    Normally websites listed in Google's results pages are shown with a standard excerpt comprising two lines with a [...] at the end of the second line. Occasionally Google allows the website a full sentence without a [...] and in these cases the excerp

  • Install Acire and Python Snippets 2011-06-15

    I'm trying to install Acire and Python Snippets in Ubuntu 11.04 (64-bit). I have successfully installed Acire, but I'm unable to install the python-snippets package. Both PPA's have been added to my sources list, but when I run sudo apt-get update, I

  • Redundant Parameters in Google Analytics JS Snippet 2013-08-06

    Google Analytics provide this snippet of code to copy and paste to a site: <script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getEl

  • Rich Snippet appears in Google's testing tool, but does not appear in Google Search 2013-08-21

    I have created a simple test page to test Microdata. When tested in Google's Structured Data Testing Tool it appears as it should, displaying the address and job title below the green URL in the search result. Now when I test this in Googl

  • Google Rich Snippets indexing fall 2013-12-05

    To 12th November 2013 there were about 3000 pages with structured data indexed for our site according to Google Webmaster Tools. There were stars and all related information in search results. But after the 12th, a sharp drop began in indexing and at

  • Using Google API within Python and applying to ArcMap? 2015-06-15

    I am currently doing a practical project at university (MSc in GIS). I have to develop a python script and the functionality of this script has been left very open other than we have to use Python only and with ArcMap. I'm have use ArcMap and Python

  • Parsing a messy xml file and extracting some specific fields of it using python 2009-12-16

    I have many rows in a database that contains xml and I'm trying to write a Python script that will go through those rows and count how many instances of a particular node attribute show up. For instance, my tree looks like: <foo> <bar> <typ

  • Code snippet manager for Ubuntu? 2010-10-11

    I'm looking for a good code snippet manager, with syntax highlighting and search capabilities. Another important feature is the capability of changing the code area background color. I have tested some Adobe Air apps that had white background everywh

  • Golf Practice: Python 2014-11-18

    This is a challenge of practicing golf optimization in Python -- reusable tricks and shortcuts to shave off a few characters. Many will be familiar to Python golfers and use common ideas from the Python Tips. Some of these use Python-specific feature

  • Don't google "google" 2015-09-28

    We all know that if you google the word "google" it will break the internet. Your task is to create a function that accepts 1 string and returns its length, in as few amount of Unicode characters as possible. However, if the given string is goog

iOS development

Android development

Python development

JAVA development

Development language

PHP development

Ruby development


Front-end development


development tools

Open Platform

Javascript development

.NET development

cloud computing


Copyright (C), All Rights Reserved.

processed in 0.920 (s). 13 q(s)