Please Help: Python String Reverse Challenge


#1


https://www.codecademy.com/en/courses/python-intermediate-en-rCQKw/1/1?curriculum_id=4f89dab3d788890003000096#

My code works, but I'm new to programming and I have no idea what the best practices are for formatting, style, variable and function names, etc.

My approach to this problem was to:
1) Convert the string into a list
2) Use the list to create a new reversed list
3) Convert the reversed list back into a string

I don't know whether my logic is redundant or inefficient.

If you have experience developing in Python and could review my code, I'd really appreciate it.

def reverse(text):
    word = []
    for letter in text:
        word.append(letter)

    word_reverse = []
    count = 1
    for letter in word:
        a = len(word) - count
        b = word[a]
        word_reverse.append(b)
        count += 1
    
    a = str()
    for letter_reverse in word_reverse:
        a += letter_reverse
    return a


#2

I already found one problem, instead of:

def reverse(text):
word = []
for letter in text:
word.append(letter)

I can just do:

def reverse(text):
word = list(text)


#3

why would you want to convert to list? I don't see the value

you can simply use text in your loop:

for letter in text:
        a = len(text) - count
        b = text[a]
        word_reverse.append(b)
        count += 1

if you really want to optimize, make a variable contain the length of text outside the loop. This way, the length of text doesn't have to be calculated every iteration of the loop

finally, strings are immutable in python, so to get from your reversed list to string, i really recommend the build in .join() function


#4

Thanks so much Tim (correct?),

I've implemented your recommendations below. Any other advice?

`python

def reverse(text):

word_reverse = []
length = len(text)
count = 1

for letter in text:
    a = length - count
    b = text[a]
    word_reverse.append(b)
    count += 1
    
x = ""
return x.join(word_reverse)

#5

This is already much better :slight_smile:

You can progress now, and come back later, then you learned more, then you might be able to optimize it even moer


#6

Awesome thank you so much!


#7

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