Original question (which has been solved): Assuming a simplified football scoring system where you can score {2, 3, 7} points, what are all the possible ways that you can score given a number of points?
Link to that question here
I am trying to wrap my head around the way these recursive functions maintain the score and results variable in the code below.
Code solution (by ggorlen):
def find_scoring(points, ways_to_score=[2, 3, 7]):
def score_finder(points, scores, result):
if points == 0:
result.append(scores[:])
elif points > 0:
for val in ways_to_score:
scores.append(val)
score_finder(points - val, scores, result)
scores.pop()
return result
return score_finder(points, [], [])
This works beautifully, and fully answered my original question. But after reading some problems in Elements of Programming Interviews (Python), I decided to play around with the way I pass the results and scores list. I emulated a technique by the author by not passing results list every time I call the function recursively, but instead assign a default value of the empty list:
def find_scoring2(points, ways_to_score=[2, 3, 7]):
def score_finder(points, scores, result = []):
if points == 0:
result.append(scores[:])
elif points > 0:
for val in ways_to_score:
scores.append(val)
score_finder(points - val, scores)
scores.pop()
return result
return score_finder(points, [])
This produced the same results and the idea came from EPI page 235 (generating balanced parentheses).
I then decided to change the way the scores variable was created to get rid of the need to pop from the list. I didn't understand the code, but again I copied the idea from the same book.
def find_scoring3(points, ways_to_score=[2, 3, 7]):
def score_finder(points, scores, result = []):
if points == 0:
result.append(scores[:])
elif points > 0:
for val in ways_to_score:
#scores.append(val)
score_finder(points - val, scores + [val])
#scores.pop()
return result
return score_finder(points, [])
So my questions are: 1. How do I wrap my head around the results variable being set to the empty list each time, and still producing the right solution? Is there some video or reference that would help me see how this works? 2. Why does the behavior of the scores variable change when I switch from appending, to just adding a value to my list?