def recursion(x):
answer = 0
if( x > 10 ):
answer +=1
return recursion( x - 1)
return answer
recursion(15)
我只是在玩python和递归函数并制作了这个,但奇怪的是有错误。
为什么打印0而不是我预期的答案:
5
答案 0 :(得分:3)
你需要为你的答案添加递归调用,而不是将其返回
def recursion(x):
answer = 0
if( x > 10 ):
answer = answer + 1 + recursion( x - 1)
return answer
有时单步执行代码是有帮助的...调试器可以很好地执行此操作,但您也可以使用pythontutor.com来可视化执行。
this will visually show you what happened with your old code and why it was broken
答案 1 :(得分:1)
你需要回答一个全局变量:
answer = 0
def recursion(x):
global answer
...
答案 2 :(得分:1)
发生的事情是,每次递归调用函数时,answer的值都设置为0.您可以将其更改为:
def recursion(x):
if( x > 10 ):
return 1 + recursion(x - 1)
return 0
更好的实施方式是:
max-width
答案 3 :(得分:1)
因为您定义的answer
位于本地范围内。
这意味着此函数调用中的answer
与上次调用中的def recursion(x , answer):
if( x > 10 ):
answer +=1
return recursion( x - 1 , answer)
return answer
print(recursion(15 , 0))
不同。
您的代码应为
Imports MySql.Data.MySqlClient
Module mdlConnect
Public cn As New MySqlConnection
Public mycom As New MySqlCommand
Public myr As MySqlDataReader
Public fail As String
Function sqlconnect(ByVal strS As String, ByVal strU As String, ByVal strP As String) As Boolean
Try
cn.ConnectionString = "SERVER=" & strS & "; USER ID=" & strU & ";Password=" & strP & ""
cn.Open()
Return True
Catch ex As Exception
fail = ex.Message
Return False
End Try
End Function
Function command(ByVal strQ As String) As Boolean
Try
mycom.Connection = cn
mycom.CommandText = strQ
mycom.ExecuteNonQuery()
Return True
Catch ex As Exception
fail = ex.Message
Return False
End Try
End Function
End Module
答案 4 :(得分:0)
因为你的答案是一个局部变量,每次调用该函数时,都会有一个“新答案”,就像那样:
递归(15):answer = 0回答+ = 1
递归(14):answer = 0回答+ = 1
...
recursion(10):如果然后将answer = 0返回到递归的回答(11), 然后去递归(12)...... 你的计划的正确方法应该是:
answer = 0
def recursion(x):
global answer
if( x > 10 ):
answer +=1
return recursion( x - 1)
return answer
答案 5 :(得分:0)
变量answer
总是返回0。
更好的解决方案是:
def recursion(x, answer):
if( x > 10 ):
answer +=1
return recursion( x - 1, answer)
return answer
recursion(15, 0)