7/15 reverse


#1



Um . . . can someone explain why this code is not accepted by Codecademy?


    # Instructions
    # Define a function called reverse that takes a string textand    returns that string in reverse.

    # For example: reverse("abcd") should return "dcba".

    # You may not use reversed or [::-1] to help you with this.
    # You may get a string containing special characters (for example, !, @, or #).

    def reverse(text):
        result = ''
        count = len(text) -1
        for x in text:
            result += text[count]
            count -=1
        return result
    
    reverse("abcd")


The code definitely is working, but Codecademy says, "Oops, try again. Hey now! No using [::-1] or reversed()."

I didn't use [::-1] or reversed(), so WHY is this not accepted?


#2

Hey buddy there is a simpler way to do it, that helps you understand what's happening with the text.

def reverse(text):
    # We need an empty string to store the new reversed text
    new_text = ""
    
    # Note: When using the range function with strings or lists you dont have to type "for i in range(0, (len(text)):"
    for i in range(len(text)):   
        new_text += text[len(text)-1-i]
    return new_text

#3

I myself was confused with what had to be done, but going back to see previous lessons and your code helped me find a good solution with while loops. Thanks for the assistance! If you were wondering, here is the solution:

def reverse(text):
    RevWord = ''
    pos = len(text) - 1
    while pos >= 0:
        RevWord += text[pos]
        pos -= 1
    return  RevWord

#4

Sorry . . . nevermind, I solved it. I just removed this part:


    # Instructions
        # Define a function called reverse that takes a string textand    returns that string in reverse.

        # For example: reverse("abcd") should return "dcba".

        # You may not use reversed or [::-1] to help you with this.
        # You may get a string containing special characters (for example, !, @, or #).


and it worked!

#6

This topic is solved.