[Tutor] Python backwards program (fwd)

Tony Meyer tameyer at ihug.co.nz
Wed Apr 13 07:10:39 CEST 2005


> I have read about loops, strings, tuples.  I am taking this 
> class on distance education and I am lost with this 
> assignment.  I have read what Tony has wrote and that does me 
> no good.  I do not understand what he is talking about.

Which bits?  The whole lot?  I teach university students programming, so
maybe the language doesn't fit with you.  Whatever it is, just say what
doesn't make sense and I'll happily rephrase it, or expand, or whatever is
needed.

> I understand how slicing works and what the numbers mean.  I 
> know what the -1 and such like that mean.  I know what the 
> len function does. 

Why then do you not understand that the answer is simply this?

"""
my_string = raw_input("Prompt:")
print my_string[::-1]
"""

(I'm not trying to be offensive; I would like to know why you don't
understand that, if you understand how slicing works).

As Danny said, if you can't simply use slicing (it is pretty simple), then
you're probably after a loop.  You want to run through the string, but with
a negative step.  The most explicit way to do this is to have an index
variable that keeps track of where you are up to in the string.  Normally
this would go from 0 to the length of the string, but you want it to go
backwards, so from the length of the string to 0.  Each time around the
loop, you want the index to go down one.

So:

start index at length of string
while index has not reached 0:
    print character at string[index]
    decrease index by one

Do you see what that is doing?  It translates very simply into Python (one
of the advantages of the language):

index = len(my_string)
while index >= 0:
    print my_string[index]
    index = index -1

This will of course print out the string one character per line, which isn't
what you want.  But that's easy enough to change.

There are other ways of doing this, but I suspect something like the above
is what you are after in a beginning course.  You could, for example, build
a new (reversed) string, rather than printing it out as you go, and then
print that out.

In C, it would look something like this:

"""
for (unsigned int i=<strlen(my_string); i>=0; ++i)
{
    printf("%c", my_string[i]);
}
"""

Which is a fairly common sort of exercise when you're learning C, since C
doesn't have the nice slicing capabilities that Python does.

> I am wasting you guys time.

Not at all.  We come here to try and help.

=Tony.Meyer



More information about the Tutor mailing list