Problem with list.insert

castironpi castironpi at gmail.com
Thu Aug 28 14:51:31 EDT 2008


On Aug 28, 11:13 am, SUBHABRATA <subhabrata.i... at hotmail.com> wrote:
> Dear Group,
> I wrote one program,
> There is a dictionary.
> There is an input string.
> Every word of input string the word is matched against the dictionary
> If the word of input string is matched against the dictionary it gives
> the word of the dictionary.
> But if it does not find it gives the original word.
> After searching the words are joined back.
> But as I am joining I am finding the words which are not available in
> dictionary are printed in the last even if the word is given in the
> first/middle.
> Now, I want to take them in order.
> I am applying a thumb rule that the position of the word of the string
> is exact with the resultant string.
> So, I am determining the word which is not in the dictionary, and its
> position in the input string.
> Now I am inserting it in the target string, for this I am splitting
> both the given string and the output/result string.
> Till now it is working fine.
> But a problem happening is that if I insert it it is inserting same
> words multiple times and the program seems to be an unending process.
> What is the error happening?
> If any one can suggest.
> The code is given below:

Warning, -spoiler-.

Instead split up your inputs first thing.

trans= { 'a': 'A', 'at': 'AT', 'to': 'TO' }
sample= 'a boy at the park walked to the tree'
expected= 'A boy AT the park walked TO the tree'

sample_list= sample.split( )
for i, x in enumerate( sample_list ):
	if x in trans:
		sample_list[ i ]= trans[ x ]

result= ' '.join( sample_list )
print result
assert result== expected

Then replace them as you visit each one, and join them later.



More information about the Python-list mailing list