-2

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

Gabriel
  • 146
  • 1
  • 2
  • 10
  • 1
    Define "similar". – timgeb Jan 17 '22 at 17:13
  • Similar meaning equal for example so much appears two times and they are equal. I changed to equal for better understanding. – Gabriel Jan 17 '22 at 17:13
  • Duplicate of [How do I check if there are duplicates in a flat list?](https://stackoverflow.com/questions/1541797/how-do-i-check-if-there-are-duplicates-in-a-flat-list). – timgeb Jan 17 '22 at 17:15

2 Answers2

1

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})
Tom Aarsen
  • 1,170
  • 2
  • 20
  • 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". – Gabriel Jan 17 '22 at 17:19
  • 1
    @Gabriel, `Counter(strings).most_common()` – Olvin Roght Jan 17 '22 at 17:21
  • 1
    I've updated my comment to respond to your question. – Tom Aarsen Jan 17 '22 at 17:22
0

You can do this without extra data structures: sort the list and scan it (single loop) to check if there are equal successive elements. You can also count the duplicates, or remove them.