-2

I'm trying to count the number of inversions in a long text file with Python. I keep getting an error on the line with left = sortCount(alist, len1, i)

import csv


def mergeCount(alist, i, len1, len2):
    print("Merge")
    inv = 0
    temp = []
    index1 = i
    index2 = i + len1

    while index1 < i + len1 and index2 < i + len1 + len2:
        if alist[index1] <= alist[index2]:
            temp.append(alist[index1])
            index1 += 1
        else:
            temp.append(alist[index2])
            index2 += 1
            inv += i + len1 - index1

    if index2 == i + len1 + len2:
        temp.extend(alist[index1 : i + len1])
    else:
        pass

    write = i
    for value in temp:
        alist[write] = value
        write += 1

    return inv


def sortCount(alist, n, i=0):
    #print("Sort")
    if len(alist) <= 1:
        return 0
    else:
        len1 = n // 2
        len2 = n // 2 + n % 2
        left = sortCount(alist, len1, i)
        right = sortCount(alist, len2, i + len1)
        mergeInv = mergeCount(alist, i, len1, len2)

        return left + right + mergeInv

def safeint(val):
   try:
      return int(val)
   except ValueError:
      return val

alist = []

with open('IntegerArray.txt') as f:
    lines = csv.reader(f, delimiter='\n')
    for line in lines:
        line = map(safeint, line)
        alist.append(line)

print sortCount(alist, len(alist), 0)
  • What error do you get? – Mathias Rav Oct 25 '15 at 08:30
  • 1
    The way you asked the question indicates a deep and fundamental problem with your approach to programming. You did not include the error message. You just said, that an error occurred. Error messages contain information that explain the error. Reading and understanding error messages is a vital pre-requisite for debugging. Please stop ignoring the content of error messages. – David Heffernan Oct 25 '15 at 08:32
  • Also try this to analyze your program here [link](http://www.pythontutor.com/visualize.html#mode=edit) – python Oct 25 '15 at 08:32
  • I'm using the IDLE Python 2.7 IDE and it isn't giving me a message... I would have written it but I cannot find an error message. It's just in red text – bigfoot675 Oct 25 '15 at 22:00

1 Answers1

1

When len1 becomes zero, you are continuously calling left = sortCount(alist, 0, i) this same thing again and again.

if len1==0 return 0

if len1==0:
        return 0

left = sortCount(alist, len1, i)
right = sortCount(alist, len2, i + len1)

Modify your sortCount like bellow:

    def sortCount(alist, n, i=0):
    if len(alist) <= 1:
        return 0
    else:
        len1 = n // 2
        len2 = n // 2 + n % 2

        if len1==0:
            return 0

        left = sortCount(alist, len1, i)
        right = sortCount(alist, len2, i + len1)
        mergeInv = mergeCount(alist, i, len1, len2)
    return left + right + mergeInv
Shahriar
  • 13,460
  • 8
  • 78
  • 95