March 14, 2014
Printing Words
Problem
Given an input text file as in the example below
1 2 3 4 5 6 7 8 9 |
I 1:1 Work 1:2 At 1:3 NetApp 1:4, 2:1 Is 2:2 Good 2:3, 3:1 To 3:2 See 3:3 You 3:4 |
Write a script that prints the output below
1 2 3 |
I Work At NetApp NetApp Is Good Good To See You |
Solution
Each line in the file contains a word and a list of positions at which the word is repeated in the printed output. Here is a python implementation:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
import re # Preallocate an array of 10x10 to store # the words in their correct order output = [[0] * 10 for i in range(10)] # Read file line by line for l in open('input.txt'): # Get line strip off white space and split using space as separator line = l.rstrip().split(' ') # Word is first token word = line[0] # Word positions rest of the line positions = line[1:] # For each position for pos in positions: # Remove the comma from the position token pos = re.sub(',', '', pos) # Get the x and y for each position x = int(pos.split(':')[0]) y = int(pos.split(':')[1]) # Copy the word into its correct cell in the output array output[x][y] = word # Print the words in order for row in output: for w in row: if w != 0: print w, if len(set(row)) > 1: print '\n' |