+ 2

How can I check if 2 strings have the same characters but not in the same positions?

Is there a class that can do it for us that can check if the 2 strings have the same characters but not in the same positions? For example: cold and dclo would be True. But, cold and dcloo would be not True because the are not the same length!

15th Aug 2020, 10:58 AM
BatOchir Artur
BatOchir Artur - avatar
3 ответов
+ 3
A very simple algorithm would be to sort the letters of the two strings alphabetically, and see if they match. In Python you could probably use collections.Counter to do this, that makes a dictionary from the letters and adds the count (number of occurrences).
15th Aug 2020, 11:03 AM
Tibor Santa
Tibor Santa - avatar
+ 3
In Python 3 you could convert both strings to set. Since sets don't have any order, you could use the equality operator (==) to compare them and also compare the length of the strings. The solution would look something like this: s1 = "cold" s2 = "dclo" s3 = "dcloo" same_chars = set(s1)==set(s2) and len(s1)==len(s2) print(same_chars) # Outputs True same_chars = set(s1)==set(s3) and len(s1)==len(s3) print(same_chars) # Outputs False
15th Aug 2020, 12:28 PM
Ali Shah Jindani
Ali Shah Jindani - avatar
+ 2
Try this in python It will check the length each time tho ,you can also check the length first then return false if length is not same otherwise continue with the following code by removing and condition print(all(True if i in b and len(a)==len(b) else False for i in a))
15th Aug 2020, 11:14 AM
Abhay
Abhay - avatar