1

I am trying to solve a puzzle where I have broken it down into 2 separate problems that both require recursion. When the 1st recursive problem is solved I want to then call the next recursive problem and when that is solved the puzzle is then complete. My problem is when the 1st recursive problem comes up with a solution that solves its problem but its not the right solution to solve the puzzle and the second recursive case fails.

For example if you have a puzzle C, that is broken into 2 Parts A and B. You would then use the solution for A, to solve B, and solving B would solve C.

My question is how would the recursion be setup (where the recursive calls would go so if the 2nd part failed it would then find a new solution to the 1st part)?

Scot
  • 59
  • 7

1 Answers1

0

Need to be more specific dude. But you need to check if the first solution is correct before you go to the second solution... Something like this:

def  first_sol(x):
     solving
     more solving
     answer
     if answer is correct:
        return answer
     else: 
        first_sol(x+1)

def  second_sol(x):
     solving
     more solving
     answer
     if answer is correct:
        return answer
     else: 
        second_sol(x+1)

x= initial guess
second_sol(first_sol(x))

If you want to make it more complex, put everything inside an while and as condition, it will only stop when answer == correct.

  • 1
    this is incorrect. it fixes the solution for the 1st part, and then tries to find the 2nd. but what if there's no such solution? we should try the next _1st_ part's solution then. your code does not do that. – Will Ness Sep 01 '22 at 20:24