Home > OS >  How to compare each element in the list and check if it's bigger then the element on the right
How to compare each element in the list and check if it's bigger then the element on the right

Time:10-18

hello I am struggling with this problem for school and can't get my code to do what it needs to solve this. The question is: 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. It wants me to count how many denominators are in the list.

  def extract_increasing(digits):
  countDem = 0



#check and see if there is anything in the list



if not digits:
    return 0

  #compare the first element to the one on the right of it



for x in range(len(digits)):
    for y in range(x   1, len(digits)):
      if digits[x] > digits[y]:
        countDem  = 1



 return countDem
    

CodePudding user response:

The code below should check if a number in the list is a dominator.

def is_dominator(lst, idx):
    for i in range(idx   1, len(lst)):
        if lst[i] >= lst[idx]:
            return False
    return True




digits = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for i in digits:
    print(is_dominator(digits, i))

CodePudding user response:

The error in your code is that you're adding one for the counter every time the next value meets the condition.

for x in range(len(digits)):
    for y in range(x   1, len(digits)):
      if digits[x] > digits[y]:
        countDem  = 1 

Every time digits[x] > digits[y] is met you add one to your counter. You should only add one once you checked that all values to the right meet the condition.

isDem = False
for x in range(len(digits)):
    for y in range(x   1, len(digits)):
      if digits[x] > digits[y]:
        isDem = True
      else:
        isDem = False
     #Once you went through all the values to the right you can add one to the counter
    if isDem ==True:
       countDem  = 1

Hope that helps!

CodePudding user response:

You start in the last element, and save always the max_element in every iteration, then you know always if exist some number grater than the current number. This is a little more efficient because it runs through the array only once.

def dominator(li: list):
    sol  = 0
    max_number = -math.inf
    for i in range(len(li)-1, -1,-1):
        if li[i] > max_number:
            sol =1 
            max_number = li[i] 
    return sol 

CodePudding user response:

Try list comprehension

lst = [0, 10, 2, 6, 7]

new_lst = [v for k,v in enumerate(lst) if all(v > x for x in lst[k 1:])]  

# [10, 7]

Update

def extract_increasing(digits: list) -> int:
    countDem = 0 
    for x, y in enumerate(digits): 
        if all(y > a for a in digits[x 1:]):
            countDem  = 1 
    return countDem
    
lst = [0, 10, 2, 6, 7]
extract_increasing(lst)  # -> 2
  • Related