Using max() to solve 1.7 - reverse


#1

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

def reverse(text):
      rev_text = ""
      index = range(len(text))
      while index != []:
          rev_text += text[max(index)]
          index.remove(max(index))
      return rev_text

A way to use max() function to return a reverse string. Any inputs on improving this method?


#2

Your function is pretty slow. Let's try to analyze this:

Let's call the length of text n. The code inside the while loop runs exactly n times, because it adds a letter for every letter in text. Inside the while loop there's a bigger problem. max(index) has to go trough the complete array to find the maximum of the array. In the first iteration, the length of the array is equal to n, in the second to n-1... until 1. So this program takes approximately n + (n-1) + (n-2) + ... + 2 + 1 = (n*(n+1))/2 = (n^2 + n)/2 steps (if you want to learn more about this, try learning 'Big-Oh notation'). This is pretty slow, since it can be easily optimized.

The only part of the array that you're actually using is the last element: n-1, n-2, ..., 1. You can thus just set a variable equal to the length of the string, and decrement it every time in the while loop. This way, you don't have to do the lookup of the max, since you already know it.

If you don't insist on using a while loop, try using a range based for loop (hint: range can also take a third argument, try looking it up).

I hope this helped, feel free to ask a follow up question.