Trouble with 7/15 reverse


#1
new_wordarray = []
new_word = ""
textarray = []

def reverse(text):
    textarray = list(text)
    for letter in textarray:
        new_wordarray.insert(0,letter)
    new_word = ''.join(new_wordarray)
    return new_word

It says that it inputs "Python!" but returns "!nohtyPcba" which really confuses me. I've run this code inside PyCharm and it worked for what they asked. Can someone explain why the "cba" shows up out of nowhere?


#2

Your code seems to work fine. Perhaps it's a weird glitch in the autocoder. Maybe save your code in a text document, hit the 'Reset Code' option, and paste your code again? Good luck!


#3

@forte2illinois_edu to point out the flaw in your code first try calling the function more than one like this

print reverse("Python!")# '!nohtyP' as expected
print reverse("Java")# 'avaJ!nohtyP' but expected 'avaJ'

thats not what we are looking for right.
Well that's because you defined these

new_wordarray = []
new_word = ""
textarray = []

outside the function so the first call the function will return the output as expected but making the subsequent calls will reverse that string and add it to the results of the previous calls.

to fix this yo need to pull those three variable into the function
like this

def reverse(text):
    #===================
    new_wordarray = []
    new_word = ""
    #textarray = []
    #===================
    #we can use this textarry
    textarray = list(text)
    for letter in textarray:
        new_wordarray.insert(0,letter)
    new_word = ''.join(new_wordarray)
    return new_word


print reverse("Python!")# '!nohtyP' as expected
print reverse("Java")#  'avaJ' as expected