Reverse


#1


Hi. I can't understand where the error came from my code :frowning:

This is my scheme for coding:

reverse(random_text): (def new function with one argument called reverse(variable)) : line 1
random_text->"random_text"(change variable to string): line 2
"random_text"->[r,a,n,d,o,m,_,s,t,r,i,n,g] (change string to list): line 3
[r,a,n,d,o,m,_,s,t,r,i,n,g]->[g,n,i,r,t,s,_,m,o,d,n,a,r] (change the sequence of list reversely): line 4~7
[g,n,i,r,t,s,_,m,o,d,n,a,r]->"gnirts_modnar" (change reverse list to reverse string)
print it

Is it impossible to use my 2nd lines' variable "string" to make input variable(text) to real string('text')?
or the is the 3rd line the problem?
I make it to change string('text') to list(['t','e','x','t'])


def reverse(text):
    string=str(text)
    lists=list(string)
    new=[]
    for i in range(0,len(lists)):
        lists[i]=lists[len(lists)-i]
        new += lists[i]
    return new


7. Reverse | list index out of range error
#2

My Thoughts
1) Convert text into string
2) Initialise an empty list
3) Iterate over the text and pop each element(gives the last element in the list) and append to the new list
4) lastly use the join function


#3

Thanks. I come to know that

string=str(text)
is not needed because the input(text) is given by the form of strings!
So I adjust my code and it works well.
Thanks again to your kind advice!!


#4

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.