1

I am trying to implement a SelectionSort algorithm in python, So I have created a numpy array and want to pass it as an argument in algorithm.

def SelectionSort(array=None):

    for i in range(len(array)):
        for j in range(i+1,len(array)):    
            if(array[j]<array[i]):
                array[i],array[j]=array[j],array[I]

But I got this ValueError:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-12-fddcbe25a509> in <module>
----> 1 SelectionSort(np.array([2,5,6,3,7,2,4]))

<ipython-input-11-a238fe8a1004> in SelectionSort(array, length_of_random_array)
      1 def SelectionSort(array=None,length_of_random_array=None):
----> 2     if(array==None):
      3         array = np.random.randint(-10000,10000,size=length_of_random_array)
      4 

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

I think it is trying to apply algorithm on each element of array.

2 Answers 2

1
 1 def SelectionSort(array=None,length_of_random_array=None):
----> 2     if(array==None):
      3         array = np.random.randint(-10000,10000,size=length_of_random_array)
      4 

I think it is trying to apply algorithm on each element of array.

You're correct: Numpy applies operations over the entire array. Your test could theoretically result in the following ambiguous truth-value:

if (np.array([1,2,None]) == None):
if (np.array([False,False,True]):

Use is to perform None-checks. None is a singleton, so a reference check will always work.

if (<array defaulting to None> is None):
if (True):
Sign up to request clarification or add additional context in comments.

Comments

1

This code is working perfectly fine for me, just needs a return statement:

Setup:

import numpy as np

def SelectionSort(array=None):

    for i in range(len(array)):
        for j in range(i+1,len(array)):    
            if(array[j]<array[i]):
                array[i],array[j]=array[j],array[i]
    return array

Execution:

arr = np.array([1,2,3,2,1])
SelectionSort(arr)

Output:

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.