Practice Makes Perfect - Reverse - Seeking recommendations on efficiency


Hello there

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")


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


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


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


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