Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why I am not getting space in between words of my final String after I reverse the sentence in Python?

So, I am solving a Leetcode question where I am given a string and I have to reverse all the words from it and return the reversed phrase. Below is the problem statement

Given an input string s, reverse the order of the words.

A word is defined as a sequence of non-space characters. The words in s will be separated by at least one space.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Return a string of the words in reverse order concatenated by a single space.

Note that s may contain leading or trailing spaces or multiple spaces between two words. The returned string should only have a single space separating the words. Do not include any extra spaces.**

Example :

Input: s = "the sky is blue"

Output: "blue is sky the"

But the output I am getting is as follows blueisskythe. I did try to add space ahead of .join() but I am not getting output that I want . Below is my code

This is the code I wrote:

class Solution(object):
    def reverseWords(self,str1):
        ss = str1.split(' ')
        final_str = ""
        for i in range(len(ss)-1,-1,-1):
            final_str += "".join(ss[i])
        return final_str
    
if __name__ == '__main__':
    str = "the sky is blue"
    print(Solution().reverseWords(str))

>Solution :

Approach what you might like:

class Solution(object):
    @staticmethod
    def reverse_word(input_str: str) -> str:
        # Split the string into words
        words = input_str.split()

        # Reverse the order of the words
        reversed_words = words[::-1]

        # Join them
        reversed_string = " ".join(reversed_words)

        return reversed_string

if __name__ == '__main__':
    input_str = "the sky is blue"
    print(Solution.reverse_word(input_str))

My suggestion to your code:

  • Consider avoiding names that shadow built-in types, like str, as it can lead to confusion and unexpected behavior.
  • String concatenation in a loop (final_str += "".join(ss[i])
    Consider using a list to store the reversed words and then joining them.
  • Unconventional naming style (str1) and method signature
    And it’s more common to use snake_case for variable and function names in Python.
    Instead of reverseWords, you can consider the replacement with reverse_words
  • Utility of @staticmethod
    For the current context, using @staticmethod is appropriate because the ‘reverseWords’ method doesn’t rely on any instance-specific attributes or methods of the class.
    Alternatively, you could make reverse_words a class method (@classmethod) if there’s a potential future need.

Conclusion:
My suggestion is not absolutely true but it’s advisable to follow best practices to write clean, robust, reusable pythonic codebase.

Have a great day!

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading