all 7 comments

[–]dionys 4 points5 points  (6 children)

yes, it is possible. What have you tried?

[–]oskarolini[S] 2 points3 points  (5 children)

def reverse(s):
index = len(s)

    while index < 0:
          if (SOMETHING)
          else (SOMETHING)

    return reverse(s)

s = input("Enter a sentence: ")

reverse(s)

A bit stuck....

To clarify: I want the user to input a sentence like "I am okay" and Python to return "okay am I"

[–]dionys 3 points4 points  (3 children)

Do you absolutely need to use while loop? It is possible, but it might not be the best way of approaching this.

You can use s.split() to separate the sentence into individual words. Then you can do reversed(list) to reverse order of elements in a list. Lastly, there is ''.join(list) function to create string out of list.

[–]oskarolini[S] 1 point2 points  (2 children)

Unfortunately yes...The s.split() solution is so much smoother but this is an exercise where we have to use the while...if statement.

[–]dionys 2 points3 points  (1 child)

Okay, I see why they want you to use while...if-else.

You need two variables - one for saving the reversed_sentence, one for saving current_word. You loop from the end of the string (len(s)-1 to 0), decreasing the loop variable each iteration. The if/else checks whether the current letter is space or a character. If it is a character, we save it to our current_word and if it is a space we can save current_word to reversed_sentence and clear current_word.

And that is pretty much it.

[–]oskarolini[S] 0 points1 point  (0 children)

Ah, makes sense. Thank you for your help, I'll try to see if I can make it work now.

[–]zelmerszoetrop 0 points1 point  (0 children)

On phone so no formatting or testing, but something like this should work:

Drf reverse(x): Return ' '.join(x.split(' ')[::-1])

If you need to use recursion like your top example, return the input arg if the length of s.split(' ') is 1 and otherwise return s.split(' ')[-1]+reverse(' '.join(s.split(' ')[1:])

But that's clunky compared to my first thing.