David M February 2016

Numpy Deep Copy Array

I'm having some trouble copying an array using numpy. I'm running a few different sort functions and comparing run times, so I need a copy of the original array and one I modify. Here's the code I've got.

import numpy
import random

SIZE = 10
DISPLAY = True

def random_fill():
    return numpy.array([random.random()*10000 for i in range(SIZE)])

def copy(p):
    return numpy.copy(p)

def display(p):
    if (DISPLAY):
        print a
        print

def bubble_sort(array):
    temp = 0
    for i in range(SIZE, 1, -1):
        for j in range(1, i):
            if (array[j-1] > array[j]):
                temp = array[j-1]
                array[j-1] = array[j]
                array[j] = temp

a = random_fill()
b = copy(a)
display(a)
display(b)
bubble_sort(a)
display(a)
display(b)

First a and b display properly, being a random array. Then a sorts and displays correctly but b displays exactly what a is. b should remain unsorted. What's the issue here?

Answers


MSeifert February 2016

You shouldn't use print a but print p otherwise you print the global array instead of the one passed to the function.

Post Status

Asked in February 2016
Viewed 1,012 times
Voted 11
Answered 1 times

Search




Leave an answer