0

This recusion is adapted from http://www.geeksforgeeks.org/print-all-possible-combinations-of-r-elements-in-a-given-array-of-size-n/ and does indeed print out all possible unique combination of arr with length r.

What I want from it is to save all possible combination in a list to further use this algorithm in another program. Why is the values overritten in combArray in the recustion and how do I solve this?

def combRecursive(arr, data, start, end, index, r, combArray):
    if index == r:
        combArray.append(data)
        return combArray

    i = start
    while True:
        if i > end or end - i + 1 < r - index:
            break
        data[index] = arr[i]
        combArray = combRecursive(arr, data, i + 1, end, index + 1, r, combArray)
        i += 1
    return combArray

def main():
    arr = [1, 2, 3, 4, 5]
    r = 3
    n = len(arr)
    data = [9999999, 9999999, 9999999]
    combArray = []

    combArray = combRecursive(arr, data, 0, n-1, 0, r, combArray)
    print("All possible unique combination is: ")
    for element in combArray:
        print(element)

Result as of now:

[3, 4, 5]
[3, 4, 5]
[3, 4, 5]
[3, 4, 5]
[3, 4, 5]
[3, 4, 5]
[3, 4, 5]
[3, 4, 5]
[3, 4, 5]
[3, 4, 5]

What I want:

[1, 2, 3]
[1, 2, 4]
[1, 2, 5]
[1, 3, 4]
[1, 3, 5]
[1, 4, 5]
[2, 3, 4]
[2, 3, 5]
[2, 4, 5]
[3, 4, 5]
Fredrik
  • 3
  • 2
  • 4
    @Prune: I don't see any default arguments here. – user2357112 Jun 07 '17 at 21:58
  • 1
    What you want is `[list(x) for x in itertools.combinations([1, 2, 3, 4, 5], 3)]` instead of reinventing the wheel. – zwer Jun 07 '17 at 21:59
  • @user2357112: thanks ... I apparently clicked through the list too quickly. I can't edit the reference, but this issue has been handled on SO many times before. – Prune Jun 07 '17 at 22:09
  • The answer to your question is that you are *appending the exact same list every time*. `combArray.append(data)` – juanpa.arrivillaga Jun 07 '17 at 22:12
  • @Prune - You're not wrong that [this](https://stackoverflow.com/questions/575196/in-python-why-can-a-function-modify-some-arguments-as-perceived-by-the-caller) has [come](https://stackoverflow.com/questions/2322068/python-passing-list-as-argument) up many [times](https://stackoverflow.com/questions/7379991/python-unintentionally-modifying-parameters-passed-into-a-function). – John Y Jun 07 '17 at 23:43

1 Answers1

0

You initialize data, and from then on make changes to it & add it to combArray, which means you are always adding the same array to combArray, so all of its elements are the same. If you want the elements to be distinct arrays, you need to make a new array for each you want to add to combArrays (by, for example, making a copy of data).

Scott Hunter
  • 48,888
  • 12
  • 60
  • 101
  • I.E a solution would be to change `combArray.append(data)` to `combArray.append(data[:])`. Great, thanks! – Fredrik Jun 07 '17 at 22:42