7. Reverse


#1

Excercise 7. Reverse (Link to exercise)

I’m having problems with these practice problems. The code below prints:

P y t h o n !
P y t h o n !
P y t h o n !
P y t h o n !
P y t h o n !
P y t h o n !
P y t h o n !
[’!’, ‘n’, ‘o’, ‘h’, ‘t’, ‘y’, ‘P’]

with error message:
Your function fails on reverse(“Python!”). It returns “[’!’, ‘n’, ‘o’, ‘h’, ‘t’, ‘y’, ‘P’]” when it should return “!nohtyP”.

I am trying to remove the ’ ’ and the brackets, but I’m not succeeding. Thank you in advance for your help.

def reverse(text):
    length = len(text)
    reverse_list = []
    for word in text:
        length -= 1
        reverse_list.append(text[length])
        print " ".join(text)
    return reverse_list
    
print reverse("Python!")

#2

It looks like I solved it! The only thing is that I’m not entirely sure I understand what’s happening. I will try to read it line by line. Please correct me if I’m wrong.

I defined the function, reverse, with parameter, text. I defined length as the length of the parameter. I created a list, reverse_list, to place each letter in. My for loop cycles through that parameter backwards by 1 unit with the line, length -= 1. I then append each iteration to the empty list that I created, reverse_list. I return the list with that 7th line. I’m not sure what it’s doing, but I learned in a previous exercise that you can remove quotes what this line. It’d be nice to get an explanation on this, if possible!

Lastly, I instructed to print the parameter, “Python!”

def reverse(text):
    length = len(text)
    reverse_list = [ ]
    for word in text:
        length -= 1
        reverse_list.append(text[length])
    return "".join(reverse_list)
    
print reverse("Python!")

#3

.join() is a built-in function which joins a list into a string, the character between the quotation marks is used to fill the gap:

print "-".join([7,8,2017]) # outputs: 7-8-2017

#5

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.