Python - 编写一个以字符串作为参数并向后显示字母的函数,每行一个

时间:2010-10-10 17:31:02

标签: python traversal while-loop

这是“如何像计算机科学家一样思考”的练习。我正在学习Python /编程,我不知道如何完成这项任务。

这是书中展示字母前进的一个例子,我无法弄清楚如何获得相反的效果。必须使用while循环。

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

3 个答案:

答案 0 :(得分:4)

嗯,这基本上是一回事,但是:

  1. 您必须从最后一个字母而不是第一个字母开始,因此您需要index = 0

  2. 而不是index = len(fruit) - 1
  3. 您必须减少索引,而不是在while循环结束时增加它,因此index = index + 1变为index = index - 1

  4. while循环的条件不同;只要index指向有效的字符索引,您就希望保持在循环内。由于indexlen(fruit) - 1开始,并且在每次迭代后得到一个更小,因此最终它将小于零。零仍然是一个有效的字符索引(它指的是字符串的第一个字符),因此只要index >= 0,您就会希望保持在循环内 - 这将是while条件。

  5. 全部放在一起:

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

答案 1 :(得分:2)

我认为最简单的方法是

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

或者,如果你想要每行一个字母

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

我认为它更好,因为join是操作字符串的标准方式,所以......

答案 2 :(得分:1)

最简单:

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

其他可能的解决方案可能是将索引作为字符串的最后一个索引。然后你将向后逐字母地读取字符串,每次将索引值降低1。然后你展示的代码snipplet可能变成:

>>> 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
>>> 

使用交互式解释器(只需在命令提示符下键入'python')可以帮助您试验这些代码片段。例如:

>>> 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
>>>