Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to count numbers less than a given number including duplicates

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading