7.reverse


#1



Oops, try again. Does your reverse function take exactly one argument (a string)? Your code threw a "unsupported operand type(s) for -: 'str' and 'int'" error.


def reverse(text):
    x=[]
    y=(-1)
    for n in range(len(text-1)):
        x.append(text[y])
        y=y-1
    return x


#2

the first problem is in this line:

for n in range(len(text-1)):

do you see it now that you know what line to look for? look at text-1, text is a string, how does string minus one works? this should be len(text) - 1


#3

text - 1 cannot be computed. We cannot do math on a string.

len(text) - 1

we can do, since both operands are now numbers.


#4

def reverse(text):
    x=[]
    y=(-1)
    for n in range(len(text)):
        x.append(text[y])
        y=y-1
    f=''.join(x)
    return f

thank u guys


#5

Would you mind explaining what you're doing in this approach? In particular, what's with the y=(-1) part? Is that how you're reversing the position of the character in the final string?


#6

I'm taking it that Python is ignoring the parens.

y = -1

is essentially the same as,

x.append(text[y - n])

A negative index starts from the right side and works from right to left. The smaller the negative number, the closer to the beginning.

 5  4  3  2  1  0   => values for `n`
 s  t  r  i  n  g
               -1  x == "g"
            -2     x == "gn"
         -3        x == "gni"
      -4           x == "gnir"
   -5              x == "gnirt"
-6                 x == "gnirts"
 values for y - n

#7

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