Connecting Tech Pros Worldwide Help | Site Map

QuickSort Algorithm Problem

Newbie
 
Join Date: Sep 2009
Posts: 2
#1: Sep 6 '09
Could you please help me find the error. I myself have (i might be wrong) boiled it down to the for loop because it somehow magically converts a list into an int and tries to iterate over that. But I don't know how to fix it, doesn't even make sense why it would do it. Please help me out. Thanks in advance!

Here is the error it gives me:

TypeError: 'int' object is not iterable


Here is my code:

Expand|Select|Wrap|Line Numbers
  1. import random
  2. unsortedlist = range(0,10)
  3. random.shuffle(unsortedlist)
  4. print unsortedlist
  5.  
  6. def quickSort(ML):
  7.     if ML == []:
  8.         return []
  9.     else:        
  10.         rdex = random.randint(0, (len(ML)-1)) # chose a random index for pivot
  11.         p = ML[rdex] # get the actual pivot integer
  12.         LL, GL = [],[] 
  13.         if len(ML) == 1: 
  14.             return ML        
  15.         else:
  16.             del ML[rdex]
  17.             for i in ML:
  18.                 if i < p:
  19.                     LL.append(i)
  20.                 else:
  21.                     GL.append(i)
  22.             return quickSort(LL) + list(p) + quickSort(GL) 
  23.  
  24. if __name__ == '__main__':
  25.     print quickSort(unsortedlist)
  26.  
  27.  
YarrOfDoom's Avatar
Expert
 
Join Date: Aug 2007
Location: Belgium
Posts: 1,116
#2: Sep 6 '09

re: QuickSort Algorithm Problem


What are you trying to use list() on an integer?
Newbie
 
Join Date: Sep 2009
Posts: 2
#3: Sep 6 '09

re: QuickSort Algorithm Problem


I fixed it, thanks. I guess I was looking in the wrong place and made 1 wrong assumption. Because I wanted to concatenate everything into a list, and "+" only accepts lists/strings I wanted to change the int p into a list that contains an int p. Seems like I too hastily made the analogy from using simply scheme (lisp) where you can do it by saying list(x). Python does take some stuff from scheme though. But for this particular problem it looks like to achieve the same in python you have to use the square brackets around something.
Member
 
Join Date: Nov 2008
Posts: 46
#4: Sep 24 '09

re: QuickSort Algorithm Problem


I haven't looked in detail at what you're writing, but the bisect module might be worth looking at?
Reply