I am having a problem in creating a list I am done with the logic part for radix sort . Here is the code:
import math
a = [4, 15, 7, 3, 6, 22, 45, 82]
a1 = [[] for _ in xrange(len(a))]
a2 = [[] for _ in xrange(len(a))]
a3 = [[] for _ in xrange(len(a))]
a4 = [[] for _ in xrange(len(a))]
b = [[] for _ in xrange(10)]
b2 = [[] for _ in xrange(10)]
d=len(str(max(a)))
[str(item).zfill(d) for item in a]
print a
this part of the code will add zero before the numbers so that length of all the digits will be same as that of no having max no of digit
it gives a = [ 04 , 15 , 07 , 03 , 06 , 22 , 45 , 82 ]
for x in xrange(0,len(a)) :
a1[x].append(a[x]%10)
print a1
print '\n'
this will save the end digit of each numbers as follows
a1 = [[4], [5], [7], [3], [6], [2], [5], [2]]
In the next part ,if bucket no matches with the end digits of the no. then the no. having that digit will be stored in it.
i=0
for x in xrange(0,len(a)) :
for u in range(0,len(a)) :
if a1[u]==[i] :
b[x].append(a[u])
i=i+1
for u in range(0,len(a)) :
print b[u]
Output will be as follows :
[]
[]
[22, 82]
[3]
[4]
[15, 45]
[6]
[7]
This part will pick up the no. from the bucket starting from bucket no. zero to bucket no. 10
for k in range(0,len(a)) :
l=len(b[k])
for t in range(0,l) :
a2[k]=b[k][t]
print a2[k]
a2 is
22
82
3
4
15
45
6
7
but when i print it ,like this-
print a2[0]
It gives
[]
I don't want to store the empty values in that a2 list How to avoid it?
I know i have to use condition like "if bucket is empty dont put the no just continue the loop" I dont know how to write code for this.
I guess i need to add
if len(b[k][t])==0 :
continue
else :
a2[k]=b[k][t]
print a2[k]
But it's not working
Traceback (most recent call last):
File "prog.py", line 39, in <module>
TypeError: object of type 'int' has no len()
Each b[?]
is an array of integers, so b[k][t]
will be an integer, but you are trying to take its length in if len(b[k][t])==0:
.
The only way to avoid having empty elements of a2
is to not use an array; for example, a dictionary.