7.reverse My overly complicated code (works)


After a few attempts, I managed to write some code that successfully completed the task for this exercise:


Here is the code I wrote. It is functional but it seems like I could have written something more simple.

def reverse(text):
    string = str(text)
    length = len(string)
    original_list = []
    final_list = []
    for c in string:
    index = length - 1
    while index >= 0:
        index -= 1
    final_string = ""
    for i in final_list:
        final_string += i
    return final_string

Does anyone have a simpler way of doing this? I'm curious!


def reverse(text):
dl = []
for x in range(1, len(text) + 1):
return "".join(dl)

tell me if you can't get the indentation!


def reverse(text):
    for i in text:
    return "".join(string)


Why doesnt this code work?

def reverse(text):
for a in range(1,len(text)+1):
print text[-a]

ignore the indentation


def reverse(text):
x = len(text) - 1
nstr = ''
while x >= 0:
nstr += text[x]
x -= 1
return nstr


def reverse(text):
new_text = ""

for i in range(len(text)):
	new_text += text[-(i+1)]

text = new_text
return text


Try starting a counter with the length of the string, then doing a statement that adds the last to the first letter of the string.


what this index meaning ? why we need to equal it.


Here's what I did with a simple while loop:

def reverse(text):
    result = ""
    i = len(text)-1
    while i >= 0:
        result += text[i]
        i -= 1
    return result


Here's what i did

def reverse(text):
    for alpha in range(-1,-(len (text)+1),-1): 
        res += str(text[alpha])
    return res
text ='ABCD#'        
print reverse(text)

My aim was to reverse a given string without any inbuilt functions.

While looping over strings in python we find that they are circular loops,
hence for a string :
text ='ABCD#'
text[-1] is '#'
text[-2] is 'D'
text[-3] is 'C'

and so on ..........

Hence we can create an empty string say 'res' and append characters from the string 'text' one by one in the reverse order .
This is done using the range function with a step of -1 ie. range(-1,-(len (text)+1),-1):
format of range function is range (Start,Stop,Step).

Hope this was helpful !! :slight_smile:.


Here's what I did

def reverse(text):
    rev = ""
    count = 1
    for i in range(len(text)):
        rev = rev + text[len(text)-count]
        count +=1
    return rev

I have an empty string "rev" that is going to be the final reversed "text"
A count variable that will help me get indexes
A for loop, that happens for every character of the string, and every time we take an index closer to the beginning, by adding 1 to count.

Can't really explain it, it came to me out of nowhere :confused:


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