1

I would like to run the contraction algorithm on an array of vertices n^2 times so as to calculate the minimum cut of a graph. After the first for-loop iteration, the array is altered and the remaining iterations use the altered array, which is not what I want. How can I simulate pointers so as to have the original input array during each for-loop iteration?

  def n_squared_runs(array):
        min_cut, length = 9999, len(array) ** 2
        for i in range(0, length):
            # perform operation on original input array
            array = contraction(array)
            if len(array) < min_cut:
                min_cut = len(array)
        return min_cut

2 Answers2

1

The contraction() operation should create and return a new array then, and not modify in-place the array it receives as a parameter - also you should use a different variable name for the returned array, clearly if you use array to name both the parameter and the local variable, the parameter will get overwritten inside the function.

This has nothing to do with pointers, but with the contracts of the functions in use. If the original array must be preserved, then the helper functions need to make sure that this restriction is enforced. Notice that in Python if you do this:

array = [1, 2, 3]
f(array)

The array received by the f function is the same that was declared "outside" of it - in fact, all that f receives is a reference to the array, not a copy of it - so naturally any modifications to the array you do inside f will be reflected outside. Also, it's worth pointing out that all parameters in Python get passed by value, and there's no such thing as pointers or passing by reference in the language.

Community
  • 1
  • 1
Óscar López
  • 232,561
  • 37
  • 312
  • 386
1

Don't overwrite the original array.

  def n_squared_runs(array):
        min_cut, length = 9999, len(array) ** 2
        for i in range(0, length):
            # perform operation on original input array
            new_array = contraction(array)
            if len(new_array) < min_cut:
                min_cut = len(new_array)
        return min_cut
Steve Barnes
  • 27,618
  • 6
  • 63
  • 73