Practice Makes Perfect - Reverse - Seeking recommendations on efficiency


#1



Hello there

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


This code works correctly. I ask of the hive's collective knowledge: how could this code be more efficient? Are there "smarter" approaches to reversing a string?

Thank you in advance.


def reverse(text):
    count = 1
    while (len(text) - count) >= 0:
        result = ""
        for i in text:
            result += text[(len(text) - count)]       
            count += 1
            if len(result) == len(text):
                return result            
            
print reverse("fart")


#2

make result a list, strings are immutable in python, everytime you concate a string:

result += text[(len(text) - count)]

a new string with the combined result is made, lists are mutable and thus more efficient. use .join() to convert list to string


#3

Awesome response. I thought lists the better type but didn't know how to convert to strings. Cheers!


#4

ideally, find a way you only need one loop, not two.


#5

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