-
Notifications
You must be signed in to change notification settings - Fork 255
Transpose a Matrix(UPI)
LeWiz24 edited this page Aug 20, 2024
·
2 revisions
TIP102 Unit 1 Session 2 Advanced (Click for link to problem statements)
- 💡 Difficulty: Easy
- ⏰ Time to complete: 10 mins
- 🛠️ Topics: Matrix, 2D Array Manipulation
Understand what the interviewer is asking for by using test cases and questions about the problem.
-
Q: What is the input to the function?
- A: The input is a string
sentence
containing words separated by spaces.
- A: The input is a string
-
Q: What is the expected output of the function?
- A: The function should return a string where the order of the words in the input
sentence
is reversed.
- A: The function should return a string where the order of the words in the input
-
Q: How should the function handle a sentence with only one word?
- A: If the sentence contains only one word, the function should return the original string.
-
Q: What if the sentence is empty?
- A: If the sentence is empty, the function should return an empty string.
Plan the solution with appropriate visualizations and pseudocode.
General Idea: Split the sentence into words, reverse the order of the words, and then join them back together into a single string.
1) Use the `split()` method to divide the sentence into a list of words.
2) Reverse the order of the words using list slicing.
3) Join the reversed list of words back into a string using the `join()` method, separating the words by spaces.
4) Return the resulting reversed sentence.
- Forgetting to handle cases where the sentence is empty.
- Not correctly reversing the list of words.
- Returning the list of words instead of a string after reversing.
def reverse_sentence(sentence):
# Split the sentence into words
words = sentence.split()
# Reverse the list of words
reversed_words = words[::-1]
# Join the reversed list back into a sentence
reversed_sentence = ' '.join(reversed_words)
return reversed_sentence