Problem: Count the number of ways to construct sum n
by throwing a dice one or more times. Each throw produces an outcome between 1 and 6.
Solution: I have written a recursive solution for it which outputs correct answer. For large values of n
it should hit stack overflow. So I want to avoid it and rewrite the code using tail recursive approach. Here's my code:
def numWays(n, arr):
answer = 0
for item in arr:
if item <= n:
if n == item:
answer += 1
else:
answer += numWays(n-item, arr)
return answer
li = [i for i in range(1,7)]
print(numWays(5, li)) #example n=5
I've seen example of writing factorial function as tail recursive on web but that was easy. Not able to apply that accumulator trick to store the required answer as an additional argument in the function call. Are there any other tricks which work in general?
This could be rewritten as iterative function also but I am looking for ways in general to convert recursive functions to tail-recursive. The given problem, code, and Python is just for an example. Nothing specific about those.