Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

String Reverser

Hey there, Below there are three different function which return same results but I want to know which one is good for time consuming and if you can explain Big O() also it would be really help full.

#Test1
def string_reverser(our_string):
    new_string = ""

    for i in range(len(our_string)):
        new_string += our_string[(len(our_string)-1)-i]
    return new_string
print ("Pass" if ('retaw' == string_reverser('water')) else "Fail")

#Test2
def string_reverser1(our_string):
    return our_string[::-1]
print ("Pass" if ('!noitalupinam gnirts gnicitcarP' == string_reverser1('Practicing string manipulation!')) else "Fail")

#Test3
def string_reverser3(our_string):
    return ("").join([our_string[(len(our_string)-1)-i] for i in range(len(our_string))])
print ("Pass" if ('3432 :si edoc esuoh ehT' == string_reverser3('The house code is: 2343')) else "Fail")

1 Answer

Steven Parker
Steven Parker
229,608 Points

I'd bet the slice is the fastest (as well as most compact); but if you really want to know for certain, there are a number of benchmarking tools available for Python. But be sure to test your versions using the same string when benchmarking.

That "Big O" notation can be a bit strange at first. Try taking a break from it, and when you review the material again you might get an "Aha!" moment. :wink: