7. reserve


#1

https://www.codecademy.com/courses/python-intermediate-en-rCQKw/1/1

My error message:
File "python", line 8, in
File "python", line 3, in reverse
NameError: global name 'reserved' is not defined

I expect my program will give me an answer of reversed letters

def reverse(text):
    letters = list(text)
    reserved.letter = []
    count = 1
    for i in range(0,len(text)):
        count = len(text) -1 
    return " ".join(reserved.letter)
print reverse("abcd")

#2

Using a dot . in a variable is a bad idea:

reserved.letter

use a underscore instead:

reserved_letter

Now i am going to take a look at your code


#3

okay, i added a print statement:

def reverse(text):
    letters = list(text)
    reserved_letter = []
    count = 1
    for i in range(0,len(text)):
        count = len(text) -1 
        print letters[count]
    return " ".join(reserved_letter)
print reverse("abcd")

count will always be 3, and you never pushing anything into reserved_letter, what exactly is your plan?


#5

my plan of reversing the text is
1. turn the text into a list
2. then output the list from backward by using the index

I think this way is possible to get a reversed text


#6

So, without using a built in method, take a string, make it into a list, then iterate from the last element to the first and build an output list. What if we created a mutable list from the input list, and then popped data from the original into a reverse list?

def find_uniques(x):
    words = x.split(' ')
    uniques = []
    for word in words:
        if word not in uniques:
            uniques.append(word)
    return uniques

print find_uniques("The quick brown fox jumps over the lazy dog")

def reverse(x):
    y = x[:]
    k = []
    while len(y):
        k.append(y.pop())
    return ' '.join(x), k

print reverse(find_uniques("The quick brown fox jumps over the lazy dog\n"))
'''
['The', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog']
('The quick brown fox jumps over the lazy dog\n', 
['dog\n', 'lazy', 'the', 'over', 'jumps', 'fox', 'brown', 'quick', 'The'])
'''

#7

It is possible, but in your case count is always 3 (the last letter), so you need to find another way to get the last letter (len will always be 4)

You can loop over the list in reverse order with:

count = len(text) -1 - i

we use the i in the for loop very clever here. Then you can append items to your new list


#8

i dun really understand what's the use -1 inside the formula, mind to explain more? what effect will it lead to?

THX!!


#9

len is 4, while the items are indexed at 0,1,2 and 3. So you need minus one to get the right index:

for i in range(0,len(text)):
   print text[len(text) - 1 -i]