Skip to content
Advertisement

Python3 running the same function with the same input many times but producing different outputs every time

I am currently trying to solve a simple version of checkers with python. Specifically, I am trying to solve the problem “checkers” from USACO 2008 December Bronze contest. (Problem Link)

My idea is to run a recursive dfs function on the location of each of the kings. However, I have encountered some issues with my dfs function. When I run my dfs function multiple times, the function produces different outputs, even with the same parameters. Specifically, it only produces the right outputs in the first time. I don’t know what is happening, any help will be appreciated, thank you! (I am using Python 3.7)

Here is my dfs function:

JavaScript

Here is how I called my dfs function:

JavaScript

Here is the output I am getting:

enter image description here

Here is my full code:

JavaScript

Advertisement

Answer

The .copy() list method will only work on one “layer” of the list. Since grid is a list of lists, the original will still be changed if you change the copy.

For example, try in the Python console

JavaScript

You see that a has changed, despite b being set to a.copy(). You will need to make some form of a “double” copy.

Alternatively, use the deepcopy function from copy module:

JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement