What is different approach to my problem?
Your code is heavily dependent on the assumption that the string will always contain exactly 2 spaces. The task description you provided does not say that this will always be the case.
This assumption can be eliminated by using str.join
and [::-1]
to reverse the list:
def funct1(x):
return ' '.join(x.split()[::-1])
print(funct1('short example'))
print(funct1('example with more than 2 spaces'))
Outputs
example short
spaces 2 than more with example
A micro-optimization can be the use of reversed
, so an extra list does not need to be created:
return ' '.join(reversed(x.split()))
2) is there any other way to reverse than spliting?
Since the requirement is to reverse the order of the words while maintaining the order of letters inside each word, the answer to this question is "not really". A regex can be used, but will that be much different than splitting on a whitespace? probably not. Using split
is probably faster anyway.
import re
def funct1(x):
return ' '.join(reversed(re.findall(r'\b(\w+)\b', x)))
A pythonic way to do this would be:
def reverse_words(sentence):
return " ".join(reversed(sentence.split()))
To answer the subquestions:
- Yes, use
str.join
. - Yes, you can use a slice with a negative step
"abc"[::-1] == "cba"
. You can also use the builtin functionreversed
like I've done above (to get a reversed copy of a sequence), which is marginally more readable.