Define an element of a list of items to be a dominator if every element to its right (not just the one element that is immediately to its right) is strictly smaller than that element. Note how by this definition, the last item of the list is automatically a dominator. This function should count how many elements in items are dominators, and return that count. For example, the dominators of the list
[42, 7, 12, 9, 13, 5]
would be the elements42
,13
and5
. The last element of the list is trivially a dominator, regardless of its value, since nothing greater follows it.
I am working on this practice problem and have a code that works, however it's quite slow. How can I best optimize this to run faster?
def count_dominators(items):
item_count = len(items)
count = 0
if item_count==0:
return count;
count+=1;
if item_count==1:
return count;
for i in range(0,len(items)-1):
flag=1
for j in range(i+1,len(items)):
if(items[j]>=items[i]):
flag=0;
break;
if(flag==1):
count+=1;
return count