[Tutor] swapping list elements based on some criterion

Andreas Perstinger andreas.perstinger at gmx.net
Sat Oct 8 11:34:19 CEST 2011


On 2011-10-08 11:11, Andreas Perstinger wrote:
> def swap(sentence):
>       s = sentence.split()
>       for i in reversed(range(len(s))):
>           if s[i].endswith("/N") and s[i-1].endswith("/ADJ"):
> 	    s[i], s[i-1] = s[i-1], s[i]
>       return s

Oops, noticed a little bug:

The for-loop should be "for i in reversed(range(1, len(s))):" so that 
sentences starting with a noun get processed correctly:

 >>> swap("Joe/N went/VBZ crazy/ADJ")
['Joe/N', 'went/VBZ', 'crazy/ADJ']

Bye, Andreas


More information about the Tutor mailing list