I have a task to count numbers less than a given number. I understand this for most cases except ones with duplicates. So for example a list [1,2,2,3,4] I want the out put of this to be a count of 2 since it not including the middle one
One way I’ve tried this target is the number is the given number to find the less than to
count=0
for i in list:
if i< target:
count=count+1
return count
I know if I put = it will count both twos how can I fix this with what I have now and it still being a list
>Solution :
I would first remove duplicates like this:
res = []
[res.append(x) for x in list if x not in res]
and then you could get the number of values in the list without duplicates with the len function: len(res) or check each value to make sure it meets criteria before counting like being less then a number:
count = 0
for i in res:
if i < target: count += 1
return count
Although it might be faster to create a list of numbers that are both not duplicates and meet the criteria, and then just take the length of that list:
res = []
[res.append(x) for x in list if x not in res and x < target]
return len(res)