Have you ever been asked this question in a technical interview for a software related position: "Using the language of your choice, reverse the words in a sentence."? If so, have you ever wondered how many solutions in different languages exist? Scripting, object-oriented, functional programming, commands, and the list could go on...
Thanks to Andrew for providing such a short and cool solution that might show why Linux users just love Linux and its tools! You can try this on a Linux terminal: echo "this is the sentence to reverse" | tr ' ' '\n' | tac | tr '\n' ' '; echo
Let me know what you think and feel free to share your solutions!
Thanks to Andrew for providing such a short and cool solution that might show why Linux users just love Linux and its tools! You can try this on a Linux terminal: echo "this is the sentence to reverse" | tr ' ' '\n' | tac | tr '\n' ' '; echo
Fyi, tr stands for translate character, which means that it will search for all the ' ' (spaces) and replace them with '\n' (new line); tac prints a file/string in reverse, like the opposite of cat.
Let me know what you think and feel free to share your solutions!
Python:
ReplyDelete'hello world'[::-1]
'dlrow olleh'
much easier :D
Thanks for your solution but as Mariam explained below, the interview question is to reverse the order of the words rather than the letters in the string. Nevertheless, your python solution to reverse the letters in a string is definitely cool! :)
DeleteHi Marly and Andrew,
ReplyDeleteThat's such a cool linux script :) Thanks for sharing!
@anonymous: I think that the interview question means to change the order of the words not the letter: eg "Hello world" would be "world hello" :)
Mariam!! Thanks! :)
DeleteAlso thanks for the clarification about the question! ;)
So, if the order of the words should be reversed and the result should be a string, I'd go for this in Python:
ReplyDelete' '.join(SENTENCE.split()[::-1])
Andreas ;-)
Hey Andreas!
DeleteThanks for your 2nd solution! :) (I assume that was you too up there, correct me if I am wrong!)
It's so great to see how many solutions can come up from such a simple question! It also shows the strengths of some languages/tools compared to others.
Once again thank you so much for sharing your solution! :)
Even shorter: tac --separator=" "
ReplyDeleteHere's an even shorter one :P
Deletetac -s' '
I think this is the shortest answer to date, comes in at 9 characters.