7. Reverse (code returning errors when an alphabet is used twice)


#1


this code works fine when running words with just one occurrence of each alphabet but when there's more than one, then it clubs them together. could anyone tell me why?


def reverse(text):
    text_brk = []
    rev_brk = []
    for i in text:
        text_brk.append(i)
    while len(text_brk)>0:
        rev_brk.append(text_brk[(len(text_brk)-1)])
        text_brk.remove(text_brk[(len(text_brk)-1)])
    print ''.join(rev_brk)
    
    
    
    
    
reverse('Python!')


#2

in here:

text_brk.remove(text_brk[(len(text_brk)-1)])

remove method just find first accured, but your part is from end of word,
ommmm and i can say remove not need, just use a counter to access that part.
the ‚ÄĆalgorithm for this part of you code that you can use, is:
first append to new list
then use 'wordlen - counter' to access the new part.

but there are many way to reverse text and in python have better way to reverse :wink:


#3

take a look at this code (which is your code, slightly modified:

def reverse(text):
    text_brk = []
    rev_brk = []
    for i in text:
        text_brk.append(i)
    print text_brk
    while len(text_brk)>0:
        rev_brk.append(text_brk[(len(text_brk)-1)])
        print text_brk[(len(text_brk)-1)]
        text_brk.remove(text_brk[(len(text_brk)-1)])
        print rev_brk, text_brk
    return ''.join(rev_brk)
 
print reverse('raar')

raar is a dutch word (it means strange), but a perfect example of what is wrong with your code. the big problem with your code is the way remove works, remove doesn't remove index, it removes items, lets say i have a list:

lst = ['a','b','c']

i can do:

lst.remove('a')

which brings us to the problem, you remove letters, which means if there are duplicate letters (or worse, triple or even more), those letters will be removed first. I think working on index base for this problem, is a much better idea


#4

Thanks ! I wasn't aware of that issue with the remove function ! I switched to the 'del' function instead and it worked just fine!


#5

isn't it better to use pop? it works based on index and is made for lists

lst = ['a','b','c']
lst.pop(0)

either way, both will work. Good to hear the issue is resolved