Select the correct answer Observe the following Python code?def a(n): if n == 0: return 0 else: return n*a(n - 1)def b(n, tot): if n == 0: return tot else: return b(n-2, tot-2)Optionsb() is tail recursive but a() isn’t Both a() and b() are tail recursive Both a() and b() aren’t tail recursivea() is tail recursive but b() isn’t
Question
Select the correct answer Observe the following Python code?def a(n): if n == 0: return 0 else: return n*a(n - 1)def b(n, tot): if n == 0: return tot else: return b(n-2, tot-2)Optionsb() is tail recursive but a() isn’t Both a() and b() are tail recursive Both a() and b() aren’t tail recursivea() is tail recursive but b() isn’t
Solution
b() is tail recursive but a() isn’t.
Here's why:
In recursion, a function is said to be tail recursive if the recursive call is the last operation in the function. In other words, the result of the recursive call is the result of the function.
Looking at function a(), the last operation is not the recursive call a(n - 1), but rather it's the multiplication operation n*a(n - 1). So, function a() is not tail recursive.
On the other hand, in function b(), the last operation is the recursive call b(n-2, tot-2). There are no operations after this recursive call. Therefore, function b() is tail recursive.
Similar Questions
Select the correct answerObserve the following Python code?def x(num): if num == 0: return 0 else: return num*x(num - 1)def y(num, ct): if num == 0: return ct else: return y(num-2, ct-2)OptionsBoth x() and y() are tail recursiveBoth x() and y() aren’t tail recursivey() is tail recursive but x() isn’tx() is tail recursive but y() isn’t
Select the correct answerWhat is tail recursion?OptionsA function where the recursive functions leads to an infinite loopA recursive function that has two base casesA recursive function where the function doesn’t return anything and just prints the valuesA function where the recursive call is the last thing executed by the function
Which of the following function calls lead to infinite recursion in the below code?def fun(a): if(a==0): return 0 return a*fun(a-1)*fun(0)fun(9)fun(-3)None of these
Select the correct answerWhich of the following statements is false about recursion?OptionsA recursive function makes the code easier to understandInfinite recursion can occur if the base case isn’t properly mentioned Every recursive function must have a base caseEvery recursive function must have a return value
Explain recursion function in python with example
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.