简体   繁体   中英

How to convert nested loop to list comprehension?

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
sum([1 if (arr[i] > arr[j]) else 0 for i in range(n) for j in range(i+1,n)])

should work as a list comprehension answer. I had referred this stackoverflow post a few months ago to do be able to do this.

In terms of time complexity, however, it won't be better than O(N^2).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM