Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Given a sentence, return a sentence with the words reversed

def master_yoda(text):
    txt_elements=text.split()
    index=-1
    reverse=[]
    i=0
    while i <= len(txt_elements):
        reverse.append(txt_elements[index])
        index=index-1
        i+=1
    final=' '.join(reverse)
    return final
print(master_yoda('i adore that'))

I cannot understand why I keep on getting errors about unindentation.

Here is an example:

  • Input: "I am beautiful"
  • Output: "beautiful am I"
like image 601
Malik Abdullah Avatar asked Nov 24 '25 23:11

Malik Abdullah


1 Answers

Just change

while i <= len(txt_elements):

to

while i < len(txt_elements):

Bear in mind you could just do this instead:

def master_yoda(text):
    return ' '.join(text.split()[::-1])

In this example, [::-1] reverses the list using slicing. You could also use the reversed() python builtin - see comment by @wjandrea

like image 88
CDJB Avatar answered Nov 27 '25 12:11

CDJB



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!