thi开发者_JAVA技巧s is what Ii wrote so far but it is not the correct output
def characters(char):
numb=ord(char)
while numb>ord('a'):
print chr(numb),
numb=numb-1
return
I want the this output:
characters('h')
g f e d c b a
Whenever you design a recursive function, the first thing you want to ask yourself is: how does the algorithm terminate? I.e., what's the base case? In your example, the algorithm should stop printing characters after the letter 'a' is printed, so that's your base case.
Next, you have to ask how to get to the base case from your starting case. That's pretty easy: you want to print the previous character until you reach the base case. (A character is essentially just an integer, so that means you want to subtract one from the character and print it as a string.)
Putting that all together, I got:
def print_reverse(ch):
print ch,
if ch > 'a':
print_reverse(chr(ord(ch)-1))
else:
print # New line
print_reverse('h')
(If you don't know what the Python functions ord
and chr
do, look them up in the interactive interpreter using help(ord)
and help(chr)
.)
Your function should be designed to call itself if it has to be recursive:
def recurse_chars_down(char):
if char <= 'a':
print char
else:
print char,
recurse_chars_down(chr(ord(char) - 1))
>>> recurse_chars_down('h')
h g f e d c b a
Recursive :
def character(char):
print(char)
character(chr(ord(char)-1))
return
def characters(char):
if char == 'a':
return ''
next_char = chr(ord(char)-1)
return next_char+' '+characters(next_char)
>>> characters('h')
'g f e d c b a '
精彩评论