How can this be solved without using `range()`?

“”

Write a function named reverse_string that has a string named word as a parameter. The function should return word in reverse.

print(reverse_string(“Codecademy”))
should print ymedacedoC

“”
Is my answer good coding practice and wouldn’t have issues with large strings? It seemed like the most logical way to approach the task but open to ideas.

def reverse_string(word):
result = ‘’
for letter in word:
result = letter + result
return result

Ta.

1 Like

First off, your code makes sense and would look to satisfy the challenge. That’s what is important here. You studied the problem and applied what you know to arrive at a solution.

A good thing is that you did not use range, which is an index approach, but used the in iterator to READ ONLY your source string. That makes perfect sense.

As operations are considered, we only need to interate the string once over so in terms of resource use is linear. The only determing factor in how many steps will be taken is the length of the string. Yes, longer strings will take longer since there are more iterations, but over all the approach is efficient.

Linear time complexity is notated by, O(N) where N is the length of the string (number of iterations). We’re a long way from benchmarking at this point but the only other consideration here is the difference in string operations and list operations. Which is more efficient in terms of real time? They will both have the same time complexity so the question now becomes which is faster? I would contend that creating a new string each iteration is faster than inserting or appending to a list.

That will be something for you to add to your reading and extra study list. For now, be satisfied that your approach does not raise any red flags.

1 Like

This is such an interesting approach:

def reverse_string(word):
result = ‘’
for letter in word:
result = letter + result
return result

Can you please explain how it reverses the string. I don’t quite understand it.

1 Like

Of course!

So normally when I’d want to add something to a string I’d just make an empty string
string = ‘’

and write this to add the new part:
string += new_substring

(which is the same as below, just shorter)
string = string + new_substring

However, this will always put the new_substring part at the END of the existing string.

Therefore, by swapping the two parts around, each time the for loop encounters a new letter in word, it places it at the START of the string result.

Is that any clearer?

6 Likes

Awesome! Thanks so much.

Friends,
the question is - is it Okay to use this reverse fuction like this:

def reverse_string(word):
return word[-1::-1]

Indexing seems rather heavy here, but I might be wrong.

many thanks for your comments:+1:

2 Likes

You don’t even need that -1 in the initial position! return word[ : : -1] will work just fine. From the docs, concerning the notation lst[i: j: k]

If i or j are omitted or None , they become “end” values (which end depends on the sign of k )

This question comes up all of the time. In an elementary course, the instructors presumably would like to evaluate your mastery of elementary approaches. I would think that in this case, that would mean either “reverse concatenation” or indexing using range() with a step of -1.

On the other hand, should someone be penalized for taking the initiative to delve into Stack Overflow or to experiment a bit in the sandbox? I don’t really think so.

I would suggest an approach something like this:

  1. (Basic assignment) Show how to do xyz using approaches we have covered thus far.

  2. (Extra Credit) Now show five other ways to accomplish the same task.

1 Like

I just did:
def reverse_string(word):
return word[::-1]

Not sure if I was supposed to do it the other way-- using ‘for loops’ — but hey, it worked.

That way is kind of a cheat since it lets Python do all the heavy lifting. Nothing wrong, per se, but it has nothing to do with loops, and there is nothing that can be learned apart from string slicing (and hardly even that). How many other ways can you think of to reverse a string (that use iteration)?

1 Like

Hey guys, could someone help me understand why Codecademy won’t accept the code I wrote, though it seems to produce the correct output. (See attachment)

Your output string contains a blank space not present in the input string. Do you see where it comes from?

Hint: you can use print(repr(string)) to show all hidden or non-printable characters in the string.

Hi someone know, how can work this code here in this exercise:
def reverse_string(word):
return sorted(word, reverse = True)

ThANKS.

def reverse_string(word):
  word1 = ""
  for x in word:
    word1 += word[::-1]
    break
  return word1

This does the same thing, but since the loop drags on the break helps eliminate the extra iterations and returns the same result. Any insight as to what difficulties someone may have produce with a code like this or is it still a valid option? I am a beginner just testing multiple ways of producing a result.

P.S. the x looks like it is essentially doing nothing in this case other than producing the for loop.

word1 = “”
for x in word:
word1 += word[::-1]
break
return word1

Only the terms remaining without strike-through are needed for your function to work.

return word[::-1]

Not only is x doing nothing, the loop never actually runs but breaks on the first iteration.

Interesting mechanics to experiment with, though. There’s variable initialize, loop definition, string concatenation with assignment operator, string slicing and loop interruption, and of course, return. These are all learned concepts being put into practice, literally. For practice, experimentation is time well spent so long as we learn from it.

The lesson here is to be sure one understands the effect of each component in the code. In so doing one begins to know what effect to expect, and therefore whether said component is needed or not.

Suggest keep experimenting, but without string slicing. Use indices only within a for loop and see what you come up with. Hint: break will not be needed.

1 Like

Hi

easiest way to avoid using range:

def reverse_string(word):
  reverse_word = ""
  for i in word:
    reverse_word = i + reverse_word
  return reverse_word
    

Thanks, this seems like a clever approach

I see that a lot of people use a solution where they add to the string, letter by letter. I’ve tried it myself, and I don’t doubt that it works.

But I’m still puzzled, because a couple of lessons ago I learned that strings are immutable. I was told that you can’t change a string once it’s made. Still, here we change the string many times during the for loop.

Are there instances where strings are not immutable, like inside a loop? Or have I misunderstood?

No, they really are immutable all the time. The string on the right side is given another character by concatenation and the result of that expression is reassigned to the old variable. The string is not mutated, but replaced with a new string.

1 Like

Ah, of course! I think I understand now. The variable is not the string, it just contains the string. And in every loop we throw out the old content and put in a new string.

1 Like

Thinking of other ways to accomplish the task of reversing a string, I had to think of a solution involving recursion:

def reverse_string(word):
  if len(word) == 0:
    return ''
  else:
    return word[-1] + reverse_string(word[0:-1])

To explain the workings of this function, let’s first focus on the line of code after the else statement: this line will take the last character of the provided word and add to it the result of reversing the word excluding that last character. This result of reversing the word excluding the last character is obtained from a so-called recursive call, a call to the function itself.

The if statement indicates the situation in which the recursion has to stop: the case in which we are left with the empty string. Note that stopping with

if len(word) == 1:
  return word

is also possible, but does not cover the special case in which we want to reverse an empty string through the call reverse_string('').

1 Like