0

I have a working simple insertion sort algorithm written in Python. What I'm trying to do is take the output and put it in a new list without altering the original input list. I've been stuck on trying to figure out how to do this and maybe I'm just overthinking it, but I thought I would see if anyone could help. Thanks!

#!/usr/local/bin/python

import sys
import random

def RandomArray(n, max):
    A = []
    i = 1
    while i <= n:
        v = random.randint(1, max+1)
        if v not in A:
            A.append(v)
            i = i + 1
    return A

A = RandomArray(10,100)
print(A)

def InsertionSort(A):
    element = 1
    for element in range(0, (len(A))):
        w = A[element]
        j = element - 1
        while (j >= 0) & (A[j] > w):
            A[j+1] = A[j]
            j = j - 1
        A[j+1] = w
    return A

print(InsertionSort(A))
1
  • 1
    You are explicitly mutating the input array - if you don't want that to affect the original, either pass a copy (InsertionSort(A[:])) or refactor the function accordingly. Note that functions that mutate their inputs should return None by convention. Commented Sep 23, 2015 at 10:08

1 Answer 1

1

You are mutating the list in your sorting function, a simple solution with existing solution would be deepcopy the list, before mutating it.

import copy

def InsertionSort(A):
    A = copy.deepcopy(A) # or A = A[:] might work as well in this case
    ...
    return A

As an extra advice, the naming conventions you are using are not pythonic. Function names should be snake cased instead of Pascal cased (I have kept the same just for consistency).

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the help! I didn't realize it would be that easy and that there is already a module for copying

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.