[Tutor] swapping list elements based on some criterion

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

On 2011-10-08 09:53, Peter Otten wrote:
> Emad Nawfal (عمـ نوفل ـاد) wrote:
>>  Here is the function as I used it, and it works fine:
>>  def swap(sentence):
>>     buffer = []
>>     adjectives = []
>>     for word in sentence.split():
>>         if word.endswith('/ADJ'):
>>             adjectives.append(word)
>>         elif word.endswith('/N'):
>>             buffer.append(word)
>>             buffer.extend(adjectives)
>>             adjectives = []
>>         else:
>>             buffer.append(word)
>>     return ' '.join(buffer)
> Does the classification scheme allow for adjectives that are not followed by
> a noun? Example: if "good" in the sentence "That looks good" were classified
> as an adjective it would be silently dropped.

As far as I know, adjectives are always in front of a noun in English. 
Therefore I suggest iterating backwards and everytime you come across a 
noun check if it is preceded by an adjective and swap the positions. 
Iterating backwards is necessary for cases where more than one adjective 
is in front of the noun. So the noun "floats" towards the beginning of 
the sentence while all adjectives without nouns (or behind nouns - I 
don't know if that's possible in English) will stay where they are:

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

 >>> swap("the/DET tall/ADJ man/N plays/VBZ well/ADV")
['the/DET', 'man/N', 'tall/ADJ', 'plays/VBZ', 'well/ADV']

 >>> swap("That/DET looks/VBZ good/ADJ")
['That/DET', 'looks/VBZ', 'good/ADJ']

 >>> swap("He/P is/VBZ a/ART big/ADJ old/ADJ man/N who/P went/VBZ 
['He/P', 'is/VBZ', 'a/ART', 'man/N', 'big/ADJ', 'old/ADJ', 'who/P', 
'went/VBZ', 'crazy/ADJ']

Bye, Andreas

More information about the Tutor mailing list