7. reverse - What's wrong w/ my code?


#1


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

Error msg: Does your reverse function take exactly one argument (a string)? Your code threw a "unsupported operand type(s) for -: 'int' and 'unicode'" error.

Isn't the logic straight forward enough?

string = raw_input("Input text: ")

def reverse(l):
    l = list(string)
    for i in l:
        sorted(l,key=[len(string)-i])
    return l

print reverse()


#2

string = raw_input("Input text: ")

def reverse(l):
a=''
for i in range(len(l)):
a+=(l[-(i+1)])

return a

print reverse(string)


#3

no need to change your input to 'list' , bcose each letter in 'string' can also be itterable


#4

Think I'm getting closer but still not quite there...

string = raw_input("Input text: ")

def reverse():
    new = ""
    for i in range(len(string)):
        new += string[-i+1]
    return new
 
print reverse()

Gave me:
Input text: asdf
safd
None

and error:
Does your reverse function take exactly one argument (a string)? Your code threw a "reverse() takes no arguments (1 given)" error.


#5

def reverse(text):

#6

Here you go:

string = raw_input("Input text: ")

def reverse(string):
    new = ""
    for i in range(len(string)):
        new += string[-i+1]
    return new
 
print reverse(string)

Outcome:
Input text: asdf
safd
None

Error:
Your function fails on reverse("Python!"). It returns "yP!noht" when it should return "!nohtyP".


#7

Solution:

string = raw_input("Input text: ")

def reverse(string):
    new = ""
    for i in range(len(string)):
        new += string[len(string)-1-i]
    return new
 
print reverse(string)

Thanks a lot!


#8

Would you please explain your code?
i just understand till new += after that I'm duh :sweat_smile:


#9

def reverse(text):
    a = str(text)
    q = []
    tot = ''
    r = []
    for i in a:
        q.append(i)
    m = len(q) 
    for i in q:
        m = m - 1
        r.append(q[m])   
    for t in r:
        tot = tot + t
    return tot

#10

Let me try to explain it to you:

If you input string "abcd" the range function will take value of 4 which is the number of letters in the string.
The next statement, new += string[len(string)-1-i], will loop through 0 to 4 and return the letter of the string at that particular index.

In first iteration, it will be string[4-1-0] since the value of i is 0 here. It is equal to string[3]. The letter present at third index position is d in our original string so it will return that.

Similarly, all the iterations will be run till i=3. The plus sign in new+ keeps the strings together as it appends to the last returned letter.

You will get dcba as output.

Hope it helps!


#11

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