Python Challenge - Reverse Words

This community-built FAQ covers the “Reverse Words” code challenge in Python. You can find that challenge here, or pick any challenge you like from our list.

Top Discussions on the Python challenge Reverse Words

There are currently no frequently asked questions or top answers associated with this challenge – that’s where you come in! You can contribute to this section by offering your own questions, answers, or clarifications on this challenge. Ask a question or post a solution by clicking reply (reply) below.

If you’ve had an “aha” moment about the concepts, formatting, syntax, or anything else with this challenge, consider sharing those insights! Teaching others and answering their questions is one of the best ways to learn and stay sharp.

Join the Discussion. Help a fellow learner on their journey.

Ask or answer a question about this exercise by clicking reply (reply) below!
You can also find further discussion and get answers to your questions over in #get-help.

Agree with a comment or answer? Like (like) to up-vote the contribution!

Need broader help or resources? Head to #get-help and #community:tips-and-resources. If you are wanting feedback or inspiration for a project, check out #project.

Looking for motivation to keep learning? Join our wider discussions in #community

Learn more about how to use this guide.

Found a bug? Report it online, or post in #community:Codecademy-Bug-Reporting

Have a question about your account or billing? Reach out to our customer support team!

None of the above? Find out where to ask other questions here!

def word_reverser(phrase):

    words = phrase.split(" ")
    i, j = 0, len(words) - 1
  
    while i < j:
        words[i], words[j] = words[j], words[i]
        i += 1
        j -= 1

    return " ".join(words)

Steps:

  1. Splitting the phrase into a list of words
  2. Initializing two pointers
  3. As long as pointers don’t intersect:
  4. Switch words at current pointer indexes
  5. Move pointers one place in their direction
  6. Join the list back into a string with spaces in between words
1 Like

def word_reverser(phrase):
l=phrase.split(’ ‘)
reverse_phrase=l[::-1]
return (’ ').join(reverse_phrase)
print(word_reverser(‘Codecademy rules’))

This is my solution for the Reverse String question.

Steps:

  1. Split the string using the space (" ") character
  2. join the words using the space character on a reversed input string. “[::1]” will reverse the string starting from the last index to the first index.
  3. Return your new string
  4. Test the code
def word_reverser(phrase): # Write your code here words = phrase.split(" ") revWords = " ".join(words[::-1]) return revWords print(word_reverser('Test string'))

So you’ve shown that we can return it as an expression using built in tools as the promise made by the language allows.

>>> def word_reverser(phrase):
    return " ".join(phrase.split()[::-1])

>>> s = 'in through the out door'
>>> word_reverser(s)
'door out the through in'
>>> 

Imagine if we don’t have those tools and have to handle all the operations. The earlier example by @hubertstanowski relies on two str methods but illustrates the boiled down algorithm in terms of moving parts. One does find that, too, very interesting, as it were.

I was looking to solve it in three lines or less, but I understand what you’re saying. Also, I love you used a line to solve the question.

I was considering how interviewers might have certain constraints to solving the problem.

1 Like

If it were me doing the interview, there would be no constraints; but, that’s me. At 67 it won’t be me doing the interview.

1 Like
def word_reverser(phrase): return " ".join(reversed(phrase.split(" "))) print(word_reverser('Codecademy rules'))

``

def word_reverser(phrase): split_words=phrase.split(' ') words= ' '.join(reversed(split_words)) return words print(word_reverser('Codecademy rules'))
def word_reverser(phrase):
  return ' '.join(n for n in phrase.split()[::-1])
  
print(word_reverser('Codecademy rules'))
def word_reverser(sent): x=sent.split(" ") z=x[::-1] l=" " return(l.join(z)) print(word_reverser("Codeacademy rules"))
def word_reverser(phrase):
  return " ".join(phrase.split()[::-1])

print(word_reverser('Codecademy rules'))
def word_reverser(phrase): # Write your code here phrase = phrase.split(" "); combstr = "" for i in reversed(range(len(phrase))): combstr+=phrase[i]+" " return combstr[:len(combstr)-1] print(word_reverser('Codecademy rules'))
def word_reverser(phrase): list_of_words = phrase.split(" ") """if you want to see how our list looks like just run also the line commented below: print(list_of_words) """ new_phrase = "" for i in range (0, len(list_of_words)): word = list_of_words[i] new_phrase = word + " " + new_phrase #Let's remove the extra space " " at the end of our string new_phrase = new_phrase.strip() return new_phrase print(word_reverser('Codecademy rules apply here'))

You may want to see an alternative way of solving this challenge. I hope it helps. Please comment down below if you have any problems understanding the code :slight_smile:

That is an exact copy of an earlier post, that was not a submission, just a simplified form. Surely you can come up with something of your own, or are you merely collecting badges?

Exactly my solution.

  1. Split the words
  2. Reverse the words
  3. Join them by separator
def word_reverser(phrase):
  # Write your code here
  separator = " "
  words = phrase.split(" ")
  words.reverse()
  return separator.join(words)

 
print(word_reverser('Codecademy rules'))

My code:

def word_reverser(phrase):
   rev = [];
   e = phrase.split();


   for word in range(len(phrase.split())):
     rev.append(e[len(e) - word - 1]);

   return " ".join(rev);

   
word_reverser("Hello World!");

def word_reverser(phrase):
i = 0
words = phrase.split()
reversedPhrase = ‘’

for x in range(len(words)):
    i -= 1
    
    if i == -1:
        reversedPhrase = reversedPhrase + words[i]
    else: 
        reversedPhrase = reversedPhrase + ' ' + words[i]


return reversedPhrase

print(word_reverser(‘May the Fourth be with you’))

Interesting naive approach. (Naive code uses basic imperative algorithms; not an insult.)

Since x is never used, how about using i for the iteration variable and reverse the range?

 for i in range(-1, -1, -1):
                 /   |    \
        start index  |  negative stride
                  end index

The end index is actually 0 but we have to allow for the exclusion.

words[len(words) - 1] and words[-1] are the same element.

if i == -1:
    reversedPhrase = words[i]
else:
    reversedPhrase = f"{reversedPhrase) {words[i]})"

That is just a suggestion to simplify and also to get rid of reversedPhrase = ''.

1 Like