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
172,267 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: