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.
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 usesnake_casefor variable and function names in Python.
Instead ofreverseWords, you can consider the replacement withreverse_words - Utility of
@staticmethod
For the current context, using@staticmethodis appropriate because the ‘reverseWords’ method doesn’t rely on any instance-specificattributesormethodsof the class.
Alternatively, you could makereverse_wordsa 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!