I'm attempting to solve an algorithm question.
Given an array, count the number of inversions it has. Do this faster than O(N^2) time.
my first solution which doesn't satisfy O(N^2) uses nested loops:
def getInvCount(arr, n):
inv_count = 0
for i in range(n):
for j in range(i + 1, n):
if (arr[i] > arr[j]):
inv_count += 1
return inv_count
My attempt at converting to a list comprehension
def getInvCount(arr, n):
inv_count = 0
inv_count = [j for i in range (n) for j in range(i + 1, n) if (arr[i] > arr[j])]
inv_count += 1
return inv_count
I'm basing my solution on this link
I understand I'm not getting my syntax correctly, especially inv_count += 1
I have looked for examples where the nested loop needs to return a count and is written using list comprehension but I couldn't find any.
Ideally, the function should tell the number of inversions in an array like so;
def getInvCount(arr, n):
inv_count = 0
for i in range(n):
for j in range(i + 1, n):
if (arr[i] > arr[j]):
inv_count += 1
return inv_count
#testdata
arr = [1, 20, 6, 4, 5]
n = len(arr)
print("Number of inversions are", getInvCount(arr, n))
Output
Number of inversions are 5
with my current solution
def getInvCount(arr, n):
inv_count = 0
inv_count = [j for i in range (n) for j in range(i + 1, n) if (arr[i] > arr[j])]
inv_count += 1
return inv_count
#testdata
arr = [1, 20, 6, 4, 5]
n = len(arr)
print("Number of inversions are", getInvCount(arr, n))
Output
Traceback (most recent call last):
File "and.py", line 24, in <module>
getInvCount(arr, n))
File "and.py", line 16, in getInvCount
inv_count += 1
TypeError: 'int' object is not iterable