7. reverse


#1



The code does work to an extent, it reverses the words but codeacedamy won't let me pass through so I guess I must be doing something wrong. I am assuming it is because I don't put it in one line?


def reverse(text):
    index = -1
    items = len(text) 
    while 0 < items:
        print text[index]
        items -= 1
        index -= 1
    

print reverse("cunt").


#2

printing it on one line is not so difficult:

print text[index],

simply add a comma, you learned this trick, right? But that is not the problem, you need to return the reversed string, so you will need to create a string containing the reversed string, just printing one character a time won't do


#3

Great as usual Stetim! Thank you for helping out.

Solved it quite easily by creating a new variable called result and put it in as an option, then I just let the loop add each leter to the variable with result = result + text[index].

def reverse(text):
index = -1
items = len(text)
result = ""

while 0 < items:
    print text[index],
    result = result + text[index]
    items -= 1
    index -= 1
return result

print reverse("cunt")


#4

Given you already had the loop (which is the most difficult part of this program/challenge), making the required changes wouldn't be very difficult.

one more thing, in python, strings are immutable. so when you concatenate a string like you do here:

result = result + text[index]

a new string with combined result is created, not very memory efficient.

Ideally, result would be a list (lists are mutable), and after the loop use .join() to join the list into a string.


#5

Alright, re-wrote it into this. Should I have that many variables there or can I do it in a better way?

So far I have no idea how I'm affecting the hardware with my code since this is the first programming course I'm taking aside from some HTML that I tried out a while ago.

def reverse(text):
index = -1
items = len(text)
result = []
string = ""

while 0 < items:
    result.append(text[index])
    items -= 1
    index -= 1
return string.join(result)

print reverse("cunt")Preformatted text


#6

less variable != better, it might become unreadable code.

its always tricky to balance readability and performance, don't worry too much about performance, that will come later. But did want to tell you about immutable strings which takes more memory


#7

Alright thanks dude!


#8