简体   繁体   中英

Algorithm for comparisons of elements in a two dimensional array

I am creating a Python program for a company that sells iPhone accessories. The program will have a function that accepts as a parameter a list of lists, where each list element contains two values that describe a product--a price and an estimated quality (an integer value). I'd like to find a case where the price of one item is lower than another but its quality is higher than the other. So for example I will pass this list to my function:

some_inventory = [[11.95, 10], [7.95, 12], [6.50, 3],...]

In this list the element [7.95, 12] will have a lower price and higher quality than [11.95, 10]. If this case exists I'd like to return a boolean value like good_deal = True.

There is about a hundred thousand of these list elements in some_inventory. I can use a brute force method to compare each price with all other prices and then check their quality against each other, but this is very slow. I tried sorting by price first and for items with the same price I'd eliminate lower quality items and just add the highest quality item to a new list (eg, if there were items with [4.50, 2], [4.50, 5], [4.50, 8] I added only [4.50, 8] to a new list). But this still seems too time-consuming.

Is there a more efficient algorithm to do these comparisons? It doesn't have to be in python, pseudocode or C/C++ is fine.

def has_good_deal(deals):
    return sorted(deals) != sorted(deals, key=lambda x: list(reversed(x)))

The left hand side of the expression sorts the deals by their price, and if their prices are equal, by their quality. The right hand side of the expression sorts the deals by their quality, and if their qualities are equal, by their price.

If the sorts are not equal, then there are at least two deals [p1, q1] and [p2, q2] that have swapped places. If they have swapped places, p1<p2 and q1>q2 , which means that [p1, q1] is a good deal compared to [p2, q2] . If the sorts are equal, then there is no good deal.

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