Here's how to fix your first solution:
s = "I love you"
words = s.split()
def reverse_word(x):
c = list(x)
c.reverse()
return "".join(c)
result = " ".join(reverse_word(w) for w in words)
print(result)
The important things to fix are that:
- Simply calling
" ".join(c)
without making use of it somewhere doesn't help. c
is a copy of x
, and reversing it doesn't change x
.
" ".join(c)
is wrong anyway because you don't want a space between letters, so it's now "".join(c)
. The spaces are added to the actual reversed sentence.
And the second one:
s1 = []
for x in words:
new_word = []
c = list(x)
c.reverse()
for y in c:
new_word.append(y)
s1.append("".join(new_word))
result = " ".join(s1)
The important difference here is that you need a list for each word (consisting of letters) as well as for the whole sentence (consisting of words), since as you saw a single list for both doesn't work. I've kept it similar to your code but the new_word
is actually redundant since it's just an exact copy of c
. So it could be simplified as follows:
s1 = []
for x in words:
c = list(x)
c.reverse()
s1.append("".join(c))
result = " ".join(s1)
This is an extremely common pattern: create an empty list, append some element to it in each iteration of a for loop, and then keep the final result. It's so common that Python has a special syntax for it called list comprehensions:
def reverse_word(x):
c = list(x)
c.reverse()
return "".join(c)
s1 = [reverse_word(word) for word in words]
This is the more elegant, Pythonic way. In fact you'll notice now that the first bit of code above is almost exactly this, except that I immediately used s1
without even naming it, and there are no square brackets because now it's a generator comprehension and a nice little feature of Python's syntax means that just the parentheses are valid since join
only takes a single argument. But now we're getting deep, don't worry too much.
Finally reverse_word(word)
can simply be replaced by word[s::-1]
using Python's slice notation, and everything can be done in one step, and that's the solution given by AKS.