3

I have written a program for Radix Sort in Python. But when I execute the code I get following error message max() arg is an empty sequence. Here is my code:

class RadixSort:
    num=0
    array=[]

    def getData(self):
        print 'Enter the number of elements you want to enter: '
        num=int(input())
        print 'Now enter the elements: '
        for i in range(0,self.num):
            print 'Element ',i+1,': '
            value=int(input())
            self.array.append(value)

    def radixSort(self):
        bin=[[],[],[],[],[],[],[],[],[],[]]
        r=1
        m=max(self.array)
        while m>r:
            for ele in self.array:
                bin[(ele/r)%10].append(ele)
            r=r*10
            self.array=[]
            for i in range(10):
                self.array.extend(bin[i])
                bin[i]=[]       

    def displayArray(self):
        print ''
        for ele in self.array:
            print ele


RObject=RadixSort()
RObject.getData()
RObject.radixSort()
RObject.displayArray()

I get this error before entering values in array. How can I solve this?

Chris Martin
  • 30,334
  • 10
  • 78
  • 137
Prashant
  • 89
  • 1
  • 1
  • 9
  • A side note: Accessing `self.array` in your radixSort() should give you an `Attribute'Error` - you'd have to make `array = []` into `self.array = []` – deepbrook Apr 04 '16 at 09:02
  • 1
    @j4ck: `array = []` is valid, but `array` will be a class attribute, not an attribute of the instance. – Matthias Apr 04 '16 at 09:10

2 Answers2

3

I think you should replace:

num = int(input())

to

self.num = int(input())

Not superfluous will be to check that the array is not empty:

m = max(self.array) if self.array else 0
AndreyT
  • 1,449
  • 1
  • 15
  • 28
  • Or, if you're more into EAFP: use `try` and `except` to handle empty sequences. It may give a small performance boost, [depending on the nature of your input](http://stackoverflow.com/questions/1835756/using-try-vs-if-in-python); In short, if you fear that you have empty sequences regularly, use `if`; else use `try`. – deepbrook Apr 04 '16 at 09:12
0

You should show the complete traceback. When I run your code I get this:

Enter the number of elements you want to enter: 
3
Now enter the elements: 
Traceback (most recent call last):
  File "radix.py", line 35, in <module>
    RObject.radixSort()
  File "radix.py", line 17, in radixSort
    m=max(self.array)
ValueError: max() arg is an empty sequence

so m=max(self.array) fails because you can't do a max function on an object that doesn't exist. You need to have an init method to create self.array

Why are you using input and not raw_input? You are using python 2.7

joel goldstick
  • 4,393
  • 6
  • 30
  • 46