获取一个 char 并将其从 char 打印到 'a'并反转它应该是递归的
这是我到目前为止所写的,但它不是正确的输出
def characters(char):
numb=ord(char)
while numb>ord('a'):
print chr(numb),
numb=numb-1
return
我想要这个输出:
characters('h')
g f e d c b a
this 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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
每当你设计一个递归函数时,你首先要问自己的是:算法如何终止?即,基本情况是什么?在您的示例中,算法应该在打印字母“a”后停止打印字符,所以这是您的基本情况。
接下来,您必须询问如何从起始案例到达基本案例。这非常简单:您想要打印前一个字符,直到到达基本情况。 (字符本质上只是一个整数,所以这意味着你想从字符中减一并将其打印为字符串。)
将所有这些放在一起,我得到:(
如果你不知道 Python 函数
ord
和chr
可以,请使用help(ord)
和help(chr)
在交互式解释器中查找它们。)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:
(If you don't know what the Python functions
ord
andchr
do, look them up in the interactive interpreter usinghelp(ord)
andhelp(chr)
.)如果函数必须递归,则应将函数设计为调用自身:
Your function should be designed to call itself if it has to be recursive:
递归:
Recursive :