10. Reverse


#1

https://www.codecademy.com/en/courses/python-intermediate-en-rCQKw/1/1?curriculum_id=4f89dab3d788890003000096

Just curious is there a more efficient way of doing this?

word = raw_input("Type a word you want reversed:")

def reverse(text):
    n = 0
    anti_text = ""
    for char in text:
        n += 1
        anti_text += text[len(text)-n]
    return anti_text

print reverse(word)

I mean, I know that I could just do this:

word = raw_input("Type a word you want reversed:")

def reverse(text):
    anti_text = ""
    for char in text[::-1]:
        anti_text += char
    return anti_text

print reverse(word)

However, since we are not allowed to use [::-1] or reversed() in this exercise, I was wondering if there was a more efficient way of doing this other than the way I did it that the exercise would actually accept.


#2

honest answer:

Neither.

Strings are immutable in python. Which means here:

anti_text += text[len(text)-n]

a new string is created with the combined result.

if you are allowed to use [::-1] you could simply do:

def reverse(text):
  return text[::-1]
print reverse("Python")

why would you write so much code when you can use [::-1]?


#3

Ahh, I get it. Instead of looping through text[::-1] and having it return character by character, I could have just gone returned text[::-1]. Yeah, now that you mention it, the way I used [::-1] was really inefficient.


#4

yea, but [::-1] is not allowed, so what other options do we have?

Make an empty list, loop in reverse in reverse of the string using range(), append to the list, use .join() to join the list into a string after the loop has finished running


#5

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