ReverseWords question - Python

  • 0

    Here's my python code for Reverse Words in a String question:

    class Solution:
        def reverseWords(self,s):
        	x = -1
        	y = len(s)
        	output = ''
        	while x != -len(s)-1:
        		if s[x] != ' ' : 
        			x -= 1
            	elif s[x] == ' ':
            		output = output + s[x:y] + ' '
             		y = x
         	    	x -= 1
         	if x == -len(s)-1: 
         	    output += s[0:y]
    	    return output

    I've tested my code on my Mac and it works fine, however when I try to submit this piece of code to leetcode, there seems to be a runtime error:Runtime Error Message: Line 7: IndexError: string index out of range
    Last executed input: " 1 "
    I believe I can use list[-1] as the first element searching backward so I have no idea whats wrong with my code.

    Thanks for helping.

  • 4

    Only need one line of code in Python:

    return ' '.join(s.strip().split()[::-1])

  • 1

    Please do not do print in your solution, return what problem required.

    However, there is still room for improvement, after changing print output to return output in your code.

  • 0

    Thanks, I found this piece of code in discussion Q/As but this is not what I'm looking for. I just start learning Python couple days ago. Also, I believe there are other solutions to this question that is more easy to understand.

  • 0

    Thanks for your comment, I changed the print to return.
    I get a Line 7: IndexError: string index out of range error and I'm still trying to google it out.

  • 0
    class Solution:
        # @param s, a string
        # @return a string
        def reverseWords(self, s):
            str_list = filter(None,s.split(" ")) 
            #filter is to remove blank in the list, e.g. "  a    b"->"b a"
            str_list = str_list[::-1]
            a = " ".join(str_list).strip(" ")
            return a

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.