views:

73

answers:

3

This is an exercise from "How to think like a Computer Scientist". I am learning Python/programming and I'm not sure how to do accomplish this task.

Here is an example in the book that displays the letters forwards, I can't figure out how to get the opposite effect. Has to use a while-loop.

fruit = 'banana'
index = 0
while index > len(fruit):
        letter = fruit[index]
        print letter
        index = index + 1
+1  A: 

Well, it's basically the same thing, but:

  1. You have to start from the last letter instead of the first, so instead of index = 0, you'll need index = len(fruit) - 1

  2. You have to decrease the index instead of increasing it at the end of the while loop, so index = index + 1 becomes index = index - 1.

  3. The condition of the while loop is different; you want to stay within the loop as long as index points to a valid character index. Since index starts from len(fruit) - 1 and it gets one smaller after every iteration, eventually it will get smaller than zero. Zero is still a valid character index (it refers to the first character of the string), so you'll want to stay within the loop as long as index >= 0 -- this will be the while condition.

Putting it all together:

fruit = 'banana'
index = len(fruit) - 1
while index >= 0:
    letter = fruit[index]
    print letter
    index = index - 1
Tamás
+1  A: 

Simplest as:

>>> def print_reversed(s):
...   for letter in reversed(s):
...     print letter,
... 
>>> print_reversed('banana')
a n a n a b
>>> 

Other possible solution could be putting the index to be the last index of the string. Then you are going to read the string letter by letter backwards, lowering the index value by 1 each time. Then the code snipplet that you showed could become:

>>> def print_reversed2(s):
...   index = len(s) - 1
...   while index >= 0:
...     letter = fruit[index]
...     print letter
...     index = index - 1
... 
>>> print_reversed2('banana')
a
n
a
n
a
b
>>> 

Using the interactive interpreter (just type 'python' in a command prompt) could help you experiment with such code snipplets. Like for example:

>>> fruit = 'banana'
>>> len(fruit)
6
>>> len(fruit) - 1
5
>>> while index >= 0:
...   print "index at: " + str(index)
...   print "fruit[index] at: " + fruit[index]
...   index = index - 1
... 
index at: 5
fruit[index] at: a
index at: 4
fruit[index] at: n
index at: 3
fruit[index] at: a
index at: 2
fruit[index] at: n
index at: 1
fruit[index] at: a
index at: 0
fruit[index] at: b
>>> 
aeter
+1  A: 

i think that the simplest way is

print ''.join(reversed('banana'))

or, if you want one letter per line

print '\n'.join(reversed('banana'))

i think it's better because join is the standard way to operate on strings, so...

Ant