Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling
 
PerlMonks  

Re: Five Ways to Reverse a String of Words (C#, Perl 5, Perl6, Ruby, Haskell)

by stvn (Monsignor)
on Dec 12, 2006 at 15:53 UTC ( #589301=note: print w/ replies, xml ) Need Help??


in reply to Five Ways to Reverse a String of Words (C#, Perl 5, Perl 6, Ruby, Haskell)

I didn't want Python to feel left out:

def reverseWords (s): l = s.split(" ") l.reverse() return " ".join(filter(lambda x: x != '', l))
It has been a long time since I hacked python, so I am sure there is a better way to do this, but then again, there might only be one way ;)

-stvn


Comment on Re: Five Ways to Reverse a String of Words (C#, Perl 5, Perl6, Ruby, Haskell)
Download Code
Reaped: Re^2: Five Ways to Reverse a String of Words (C#, Perl 5, Perl6, Ruby, Haskell)
by NodeReaper (Curate) on Dec 12, 2006 at 17:42 UTC
Re^2: Five Ways to Reverse a String of Words (C#, Perl 5, Perl6, Ruby, Haskell)
by webfiend (Vicar) on Dec 12, 2006 at 17:46 UTC

    TMTOWTDI even in Python, these days:

    def reverseWords(words): return ' '.join([word for word in words.split()][::-1])

    I'd probably tweak it a bit in real-world code, though. Generators and list comprehensions make me go cross-eyed sometimes.

    Update: Adjusted the code to match the full goal.

      You don't need [word for word in ...]. That's just the same as map { $_ } ... in perl, an identity op on lists (more or less).

      >>> def reverseWords(words): ... return ' '.join(words.split()[::-1]) ... >>> reverseWords(" one two three four ") 'four three two one'
      [word for word in words.split()] ?
      No need for a list comprehensions here. How about this...
      def reverseWords(words): return ' '.join(words.split()[::-1])
        It is sometimes hard to not use ::-1 once learnt, but you can use reversed which makes it clearer:
        >>> def reverseWords(word):
        ... 	return " ".join( reversed(word.split()) )
        ... 
        >>> reverseWords("  one   two three four    ")
        'four three two one'
        

        - Paddy

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://589301]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others lurking in the Monastery: (13)
As of 2015-07-06 20:14 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (83 votes), past polls