Turning iteration into recursion(将迭代转化为递归)
问题描述
我想检查用户输入的string
是否有均衡数量的(
和)
的
I want to check if the string
user entered has a balanced amount of (
and )
's
例如.()(
不平衡(())
平衡
def check(string):
counter=0
string=string.replace(" ","")
if string[0] is "(":
for x in string:
if x is "(":
counter=counter+1
elif x is ")":
counter=counter-1
if counter1 is 0:
print("Balanced")
else:
print("Unbalanced")
else:
print ("Unbalanced")
所以这行得通,但是我如何通过递归解决这个问题?我试图思考每次递归调用它时如何使变量减小,一旦它为0,stop.s
so this works, but how do I solve this problem with recursion? I am trying to think how I can make a variable decrease each time i call it recursively and once it's 0, stop.s
推荐答案
算法的直接等效转换如下所示:
A direct, equivalent conversion of the algorithm would look like this:
def check(string, counter=0):
if not string:
return "Balanced" if counter == 0 else "Unbalanced"
elif counter < 0:
return "Unbalanced"
elif string[0] == "(":
return check(string[1:], counter+1)
elif string[0] == ")":
return check(string[1:], counter-1)
else:
return check(string[1:], counter)
像这样使用它:
check("(())")
=> "Balanced"
check(")(")
=> "Unbalanced"
请注意,由于 elif counter <,上述算法考虑了右括号出现在 相应的左括号之前的情况.0
条件 - 因此修复了原始代码中存在的问题.
Notice that the above algorithm takes into account cases where the closing parenthesis appears before the corresponding opening parenthesis, thanks to the elif counter < 0
condition - hence fixing a problem that was present in the original code.
这篇关于将迭代转化为递归的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:将迭代转化为递归
基础教程推荐
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 筛选NumPy数组 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01