0

This exercise involves a codeacademy problem to write a function which takes a string as an input and outputs the string in reverse, I've found solutions as to how to do it online, I'm just confused as to why mine doesnt work:

def reverse(c):
    empty=[]
    stringsize= len(c)

    for x in range(stringsize):
        empty[x]=c[stringsize-x]

    return empty
5
  • 2
    "It doesn't work" isn't much of an error description. Maybe actually look at the error you're getting? Commented Feb 5, 2014 at 13:30
  • 1
    You will get an IndexError because empty list you have does not have anything in it, it is basically empty. You should append to it. Check python docs. Commented Feb 5, 2014 at 13:30
  • incidentally, you could use the reversed function to reverse your string. something like this: "".join(list(reversed("foo"))), though there may exist even simpler solutions. I'm calling list() because reversed returns a "reversed object", which I then need to turn back into a string. Commented Feb 5, 2014 at 13:33
  • @tayfun: no, you'll get an IndexError because c[stringsize] is out of bounds; the last index is c[stringsize - 1]. Commented Feb 5, 2014 at 13:33
  • 1
    @m01: str.join() calls list on the reversed() iterator for you.. Commented Feb 5, 2014 at 13:33

5 Answers 5

4

You need to start at indexing your string from -1 through to -stringsize, and use empty.append() to add values:

for x in range(stringsize):
    empty.append(c[stringsize - x - 1])

Python indexing starts at 0, making stringsize - 1 the last index. Because empty is an empty list, you cannot index into it. Using the list.append() method adds new values at the end instead.

You don't really need the stringsize reference there, because negative indices automatically are subtracted from the length for you:

for x in range(len(c)):
    empty.append(c[-x-1])

Since this is supposed to return a string, not a list, you need to join the characters again at the end:

return ''.join(empty)

The easiest way to reverse a list is to use a negative slice stride:

def reverse(c):
    return c[::-1]
Sign up to request clarification or add additional context in comments.

8 Comments

… or even better, allocate empty beforehand: empty = [None] * len(stringsize) ;-)
@Alfe: nah, not better.
I feel it is closer to what OP tried in the first place, so, less change to his idea. He asked for reasoning why his didn't work, not for a faster solution.
@Alfe: it doesn't work because empty is empty. So there are two alternative solutions; prepopulate or list.append(). The latter is easier to explain.
Ah, I didn't think of the meaning of the name, right. But taking this into account, empty.append(…) seems to be a sin as well.
|
2

One solution :

def reverse(c):
    empty=[]
    stringsize= len(c)
    for x in range(stringsize):
        empty.append(c[-(x+1)])
    return ''.join(empty)

print reverse('string')

Another:

    def reverse(c):
    empty=[]
    stringsize= len(c)
    for x in range(stringsize):
        empty.append(c[stringsize - (x+1)])
    return ''.join(empty)

print reverse('string')

Using recursion:

    def reverse(string,start,stop):
    if start < stop - 1:
        string[start],string[stop - 1] = string[stop - 1],string[start]
        reverse(string,start+1, stop-1)
    return ''.join(string)

print reverse(list('string'), 0, len('string'))

Comments

1

In Python a string is an iterable so iterable functions can be used with it. For example reversed function:

>>> "".join(reversed("123"))
'321'

2 Comments

He asked not for a reverter but for a reason why his code didn't work.
@Alfe: I know, I saw that other answers provided a good explanation so I added an alternative. But yeah, thank you for your valuable input.
1

The least changes necessary to make your code run seem to be:

def reverse(c):
    stringsize= len(c)
    empty=[None] * stringsize

    for x in range(stringsize):
        empty[x]=c[stringsize-x-1]

    return empty

But you should reconsider your name empty (as Martijn pointed out) because that thing isn't empty (at least in the end), so the name is misleading.

Comments

1

The classic answer to this problem is to use a slice with a negative step to get what you want:

def reverse(c):
    return c[::-1]

...but maybe that's not allowed for you?

1 Comment

The OP already found other methods and just wanted to know why their own solution didn't work. You are not answering that question here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.