解释该递归如何获得字符串中的字母数量
def funk(someString):
letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz"
if someString == "":
return 0
elif someString[0] in letters :
return 1 + funk(someString[1:])
else:
return 0 + funk(someString[1:])
someString="3joe3"
print(funk(someString))
这是一个计算字符串中所有字母的函数。
所以我们定义了字母中允许的字符。
我们定义字符串并调用该函数。
在此示例中,它将首先执行 else:
部分,因为第一个元素是数字。
然后它将执行 elif:
从左侧开始的部分,因为它包含允许的字符并从那里移动。
我的问题是字符串中的字符数保存在哪里?
def funk(someString):
letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz"
if someString == "":
return 0
elif someString[0] in letters :
return 1 + funk(someString[1:])
else:
return 0 + funk(someString[1:])
someString="3joe3"
print(funk(someString))
It is a function to count all the letters in a string.
So we define allowed characters in the letters.
We define our string and we call the function.
In this example it will first execute the else:
part because the first element is a number.
Then it will execute the elif:
the part where it goes from the left as it contains the allowed characters and move from there.
My question is where does the number of characters in a string get saved?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
根据您提供的函数,它使用递归功能,在其内部调用相同的函数。当函数被调用时,它将返回值添加到其他结果中:
在此递归之后,通过以下方式感知:
她完成并返回了她添加的所有“返回值”的总和。下面是如何存储最终值或所谓的“字符数”的示例
according to the function you presented, it uses the recursion feature where it calls the same function within itself. As the function is called it adds the return to the other consequents:
After this recursion perceive through the:
She finished and returned the sum of all the "Returns" she was adding. below is an example of how to store the final value or what you called "number of characters"
递归函数是函数调用自身的特殊情况。对于新手程序员来说,这个概念通常很难掌握。
您的情况下的返回值与我们发明一个非递归示例相同,其中返回的值包含在表达式中:
输出:
3
因此,程序中的任何地方我们都看不到正在计算的值被分配给一个变量。
Python 与其他编程语言一样,使用隐藏变量来引用返回值。
A recursive function is a special case of a function calling itself. This concept is often very hard for first-time programmer to grasp.
The return value in your case is the same as if we were to invent a non-recursive example where the value being returned is contained in expressions:
Output:
3
So, nowhere in the program can we see where the value being calculated is assigned to a variable.
Python, just like other programming languages makes a hidden variable to refer to the return value.