Problem with list.insert

Terry Reedy tjreedy at udel.edu
Thu Aug 28 17:29:37 EDT 2008


SUBHABRATA, I recommend you study this excellent response carefully.

castironpi wrote:
> On Aug 28, 11:13 am, SUBHABRATA <subhabrata.i... at hotmail.com> wrote:
>-.
> 
> 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'

It starts with a concrete test case -- an 'executable problem 
statement'.  To me, this is cleared and more useful than the 20 lines of 
prose you used.  A single line English statement would be "Problem: 
Replace selected words in a text using a dictionary."  Sometimes, less 
(words) really is more (understanding).

If the above is *not* what you meant, then give a similarly concrete 
example that does what you *do* mean.

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

Meaningful names make the code easy to understand.  Meaningless numbered 
'a's require each reader to create meaningful names and associate them 
in his/her head.  But that is part of the job of the programmer.

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

It ends with an automated test that is easy to rerun should the code in 
between need to be modified.  Assert only prints something if there is 
an error.  With numerous tests, that is what one often wants.  But with 
only one, your might prefer 'print' instead of 'assert' to get a more 
reassuring and satisfying 'True' printed.

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

If you are using Hindi characters, you might want to use Python3 when it 
arrives, since it will use Unicode strings as the (default) string type. 
  But for posting here, stick with the ascii subset.

Terry Jan Reedy




More information about the Python-list mailing list