Runtime error in functions of python (list , string confusion in practice problem)

105 Views Asked by At

I have been trying to solve a particular question in my own amateur way from the Python 3 Bootcamp on Udemy. So far, there is an error, I guess, in the append() line of my code. Here I have provided you with the question and the answer to be expected. Please help me find out the error in my code.

MASTER YODA: Given a sentence, return a sentence with the words reversed master_yoda('I am home') --> 'home am I' master_yoda('We are ready') --> 'ready are We'

def master_yoda(text):
        mylist=[text.split()]
        print(mylist)
        newlist=[]
        index=-1
        for x in mylist:
            newlist.append(mylist[index])
            index=index+1
        for y in newlist:
            print(" ".join(y))
3

There are 3 best solutions below

2
On

You are using the index wrong. You start at -1, but then skip to 0, so you will choose the last element first, but then the first. Instead, use the following code:

def master_yoda(text):
    mylist=text.split()
    newlist=[]
    index = -1
    for x in mylist:
        s = mylist[index]
        newlist.append(f"{s} ")  # to add a whitespace
        index = index - 1
    sentence = ""
    for y in newlist:
        sentence = sentence + y  # add the word
    return sentence
        
print(master_yoda("Here I am"))
0
On

Your mylist is a list of list where the outer most list has only one element. Fox example, for the string "I am home", mylist becomes [["I", "am", "home"]]. So, in loop for x in mylist it iterates only once and newlist is appended with mylist[-1] which is ["I", "am", "home"]. So, when you join them, the output comes out same as the input.

Now from your problem description, it is clear that I am home becomes home am I. If you look closely, it just reverses the positions of the words in the sentence (i.e. first word becomes last, second becomes second from last and so on). So what you can do is split the sentence to get the words in list format and reverse the list and join it.

This can be done like this -

def master_yoda(text):
    mylist = text.split() # notice that [] are omitted as text.split() itself returns a list
    return " ".join(mylist[::-1])

Input:

I am home

Output:

home am I
0
On

Let me first give you what is wrong in your code for your understanding. Then I will give you different solutions that you can do to your code. Please comments in below code.

def master_yoda(text):
        mylist=[text.split()] # The [] is not needed here, this is making list of list, ex. "We are ready" becomes [["We", "are", "ready"]]
        print(mylist)
        newlist=[]
        index=-1
        for x in mylist: # this is iterating each element of mylist (only one element is there, because above code created list of list, so outer list has only one element in it)
            newlist.append(mylist[index])
            index=index+1
        for y in newlist:
            print(" ".join(y))
# But anyway from the code you have written, I can see using similar things the requirment can be fulfilled without using any for loop.

Forget all these, let us go for solution in your way and i will give you another way also.

Way 1 :

def master_yoda(text):
        mylist=text.split()
        print(mylist)
        newlist=mylist[::-1]
        print(" ".join(newlist))
            
master_yoda("We are ready")

Way 2: The below solution is in just one line without using loop and function where simply I have combined all the lines in above code to one line.

print(" ".join("I am Your".split()[::-1]))

Both the above code will give below output,

ready are we

Let me know in comment if you have any doubt.