7. Practice Makes Perfect - Old buddy trying to start again


#1

Well, as the title say I'm trying to end the course I did long time ago, and I tried a few days before posting. I think my code makes logic, but for some reason I can't even check my steps with "print". So I'm posing the code asking why or where it is wrong, thanks friends.

def reverse(text):
    word = []
    rword = []
    count = 0
    for x in text:
        word.append(x)
        count = len(word)
    for z in word:
        rword.append(word.index(count))
        count -= 1
    return rword

I tried print word and print count in the 1st for, nothing blinks out, and rword in the 2nd for and the same.

I tried too

 for z in word:
        rword.append(word.index(count))
        count -= 1
        if count == "0":
           break

If I was doing at infinite loop but I'm out of ideas. Thanks in advance.


#2

you can add print statements all you like, you just need to call the function (a function only executes when called):

print reverse("abcd")

i am confused by this:

word.index(count)

lets say we have a list:

aList = ['a','b','c','d']

index gives you the index of a element:

print aList.index('a')

would give you zero. So i am not sure how word.index(count) is going to help you.

Add some print statements so you can see what is happening (don't forget the function call), try some more, and if you are out of ideas you can always ask


#3

Well, rword.append(word.index(count)) should add to rword the letter on the "count" position on "word".

Then, if len(word) = 5, rword.append(word.index(count)) should append the 4th item list (as it starts from 0). Then, count will be one less, and print previous item list. Is the way I managed to think how can I reverse the list "word".

Also, sorry being a little dense, but how can I "print" I can't make it print work in my function.


#4

that is your plan, but as i just explained, .index() returns the index of the item:

aList = ['a','b','c','d']
print aList.index('a')

but count is already a index? So that doesn't work.

ah, i see now, i would put this line:

count = len(word)

at the same indent level as the for loop, this way, len() will count the list after all letters are appended to the list.

i was thrown on off by: count = 0, i would remove it, it serves no purpose.

but if you want to do what you are planning to, you don't need .index(), you already have index, you need to use this index to access the letters in word:

rword.append(word[count])

but be aware, arrays are zero index based (counting start from 0), so a len(['a','b','c','d']) would be 4, while the items are indexed at 0,1,2,3. You need to compensate for this.

You can just add print statements, just make sure you also call your function, otherwise no output is shown

It really has been a while since you have programmed