def countInSubList( subList ): if len( subList )==1: return 0 elif len( subList )==2: if subList[0]<subList[1]: return 0 else: temp = subList[0] subList[0] = subList[1] subList[1] = temp return 1 else: #split into recursive calls for sublists midIndex = len( subList )/2 subList1 = subList[:midIndex] subList2 = subList[midIndex:] total = countInSubList( subList1 ) + countInSubList( subList2 ) #merge step for sublists merged = list() i = 0 j = 0 mergeSteps = 0 while True: if subList1[i] > subList2[j]: merged.append( subList2[j] ) j += 1 mergeSteps += len(subList1)-i else: merged.append( subList1[i] ) i+=1 if i == len( subList1 ): merged += subList2 break if j == len( subList2 ): merged += subList1 break total += mergeSteps return total #print countInSubList( [6,5,4,3,2,1] ) intList = list() import urllib intfile = urllib.urlopen("http://spark-public.s3.amazonaws.com/algo1/programming_prob/IntegerArray.txt") contents = intfile.readlines() integerss = contents.split('\n') for i in integerss: intList.append( int(i) ) print countInSubList( intList )
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question