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 i can i traverse a list and check if an equal item contains there?

I want to ask the user to input a list of strings such as : ["i", "love you" , "so much", "so much"] and check if a equal string contains there and print the strings that most appear in ascending order. I wanted to know how could i do this either using a map or two foor loops.

I tried doing with one foor loop but is ineficient since i can’t do this the other way around. I need to do this using 2 foor lops or a map but i don’t how to implement the logic. Can anyone help me? Thanks

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 :

You can use a set for this. Sets cannot have duplicate elements, and thus if you convert a list to a set and the size of the list shrank, then there was a duplicate element. However, this only works if you do not care about which element was duplicated.

For example:

strings = ["i", "love you" , "so much", "so much"]
if len(strings) == len(set(strings)):
    print("No duplicates")
else:
    print("There was some duplicate")

Edit:

To address your comment of:

Is there a way i could print the frequency of those elements appear in the list too? Because in that way i can only now if there is a duplicate but not which duplicate it is. For example i want to print : "so much", "i", "love you".

Yes. You can use a Counter for this:

from collections import Counter
strings = ["i", "love you" , "so much", "so much"]
counted = Counter(strings)
print(counted)

which outputs

Counter({'so much': 2, 'i': 1, 'love you': 1})
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