Comma Sprinkler Problem
Anonymous User
848

I was recentlyasked this question in an interview and I was wondering if someone could help with giving a solution for this. Some solutions online list the usage of graphs but I am looking for a barebones brute force solution preferably in python

Description

Rules for adding commas to an existing piece of text are as follows:

  1. If a word anywhere in the text is preceded by a comma, find all occurrences of that word in the text, and put a comma before each of those
    occurrences, except in the case where such an occurrence is the first word of a sentence or already preceded by a comma.

  2. If a word anywhere in the text is succeeded by a comma, find all occurrences of that word in the text, and put a comma after each of those
    occurrences, except in the case where such an occurrence is the last word of a sentence or already succeeded by a comma.

  3. Apply rules 1 and 2 repeatedly until no new commas can be added using either of them.

As an example, consider the text

please sit spot. sit spot, sit. spot here now here.

Because there is a comma after spot in the second sentence, a comma should be added after spot in the third sentence as well
(but not the first sentence, since it is the last word of that sentence).
Also, because there is a comma before the word sit in the second sentence,
one should be added before that word in the first sentence
(but no comma is added before the word sit beginning the second sentence because it is the first word of that sentence).
Finally, notice that once a comma is added after spot in the third sentence, there exists a comma before the first occurrence of the word here.
Therefore, a comma is also added before the other occurrence of the word here. There are no more commas to be added so the final result is

please, sit spot. sit spot, sit. spot, here now, here.

please, sit spot. sit spot, sit. spot, here now, here.

Input

The input contains one line of text. Each character is either a lowercase letter, a comma, a period, or a space. And:
The text begins with a word.
Between every two words in the text, there is either a single space, a comma followed by a space,
or a period followed by a space (denoting the end of a sentence and the beginning of a new one).
The last word of the text is followed by a period with no trailing space.

Sample Output

Sample 1:

Input: please sit spot. sit spot, sit. spot here now here.
Output: please, sit spot. sit spot, sit. spot, here now, here.

Sample 2:

Input: one, two. one tree. four tree. four four. five four. six five.
Output: one, two. one, tree. four, tree. four, four. five, four. six five.

"""

Comments (1)
No comments yet.