reverse words

PHOTO EMBED

Tue Dec 31 2024 04:45:14 GMT+0000 (Coordinated Universal Time)

Saved by @sooraz3871 #python

def reverse_words(sentence):
    # Split the sentence into a list of words
    words = sentence.split()

    # Initialize an empty list to store the reversed words
    reversed_words = []

    # Loop through the words backwards and append each to the reversed_words list
    for i in range(len(words) - 1, -1, -1):
        reversed_words.append(words[i])

    # Join the reversed words into a single string with spaces
    reversed_sentence = ' '.join(reversed_words)

    return reversed_sentence

# Example usage
input_sentence_1 = "Hello world"
output_sentence_1 = reverse_words(input_sentence_1)
print(output_sentence_1)  # Output: "world Hello"

input_sentence_2 = "Keep calm and code on"
output_sentence_2 = reverse_words(input_sentence_2)
print(output_sentence_2)  # Output: "on code and calm Keep"
content_copyCOPY