I'm trying to compare two lists of integers, each the same size, in Python 2.6. The comparison I need is to compare the first item in List 1 with the first item in List 2, the second item in List 1 with the second item in List 2, and so on, and returns a result if ALL of the list items follow the same comparison criteria. It should behave as follows:
list1 = [1,1,1,1] list2 = [2,1,2,3] compare(list1,list2) # returns a "list 1 is <= list 2" response. list1 = [4,1,4,3] list2 = [2,1,2,3] compare(list1,list2) # returns a "list 1 is >= list 2" response. list1 = [3,2,3,2] list2 = [1,4,1,4] compare(list1,list2) # returns None— some items in list1 > list2, and some items in list2 > list1.
I figured I could write the code like the following block, but I don't know if it's the most efficient. My program is going to be calling this method a LOT so I want to streamline this as much as possible.
def compare(list1,list2): gt_found = 0 lt_found = 0 for x in range(len(list1)): if list1[x] > list2[x]: gt_found += 1 elif list1[x] < list2[x]: lt_found += 1 if gt_found > 0 and lt_found > 0: return None #(some items >, some items <) if gt_found > 0: return 1 #(list1 >= list2) if lt_found > 0: return -1 #(list1 <= list2) return 0 #(list1 == list2)
Is it already as good as it's going to get (big-O of n), or is there a faster way to go about it (or a way that uses system functions instead)?
CLARIFICATION: I expect the case that returns 'None' to happen the most often, so it is important.