Sunday, July 24, 2016

Algorithms Data and Analysis part 1

This question regards the problem of finding inversions and merge-sort. The code I used (if you don't like this code, there are numerous similar ones all over the web) to find the answer is- 
 def countInversion(alist):  
   global cnt  
   if len(alist)>1:  
     mid = len(alist)/2  
     leftHalf = alist[:mid]  
     rightHalf = alist[mid:]  
     countInversion(leftHalf)  
     countInversion(rightHalf)  
     i=0  
     j=0  
     k=0  
     for k in range(len(alist)):  
       if leftHalf[i] <= rightHalf[j]:  
         alist[k] = leftHalf[i]  
         i += 1  
         if i == len(leftHalf) and j != len(rightHalf):  
           while j != len(rightHalf):  
             k +=1  
             alist[k] = rightHalf[j]  
             j += 1  
           break  
       elif leftHalf[i] > rightHalf[j]:  
         alist[k] = rightHalf[j]  
         j += 1  
         cnt+=len(leftHalf)-i  
         if j == len(rightHalf) and i != len(leftHalf):  
           while i != len(leftHalf):  
             k+= 1  
             alist[k] = leftHalf[i]  
             i += 1            
           break   
   return alist  
 alist = [int(line.rstrip('\n')) for line in open('integerArray.txt')]  
 print 'Number of lines is', len(alist)  
 cnt = 0  
 countInversion(alist)  
 print cnt  

I get an answer which is accepted. The key thing that I got stuck on was the

line.rstrip('\n') for line in open('integerArray.txt')

If you don't cast it as an int, as in int(line.rstrip('\n')), you will get the wrong answer, because data is stored as string instead of integers. It is a rather silly mistake, but that is unfortunately the most common kind of mistake. 

No comments:

Post a Comment