Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get common characters from strings

I'm looking for the way of comparing two strings and being able to get back, as separate strings:

  • All the common characters,
  • The uncommon characters, (all characters but without the common ones)
  • Characters that are unique to one string.

Example:

A = "123 ABC"
B = "135 AZ"

thingamajigger(A, B)  # would give all these:

intersect = "13 A"  # (includes space)
exclusion = "2BCZ5"
a_minus_b = "2BC"
b_minus_a = "5Z"

a_minus_b is quite simple... but if there's one of those fancy one-liner ways to pull it off, then I'm open.

for i in B:
    A = A.replace(i, "")

It's a bit like boolean operations on strings.

like image 459
Jollywatt Avatar asked Jul 16 '13 02:07

Jollywatt


People also ask

How do you find common characters in a string?

Approach: Count the frequencies of all the characters from both strings. Now, for every character if the frequency of this character in string s1 is freq1 and in string s2 is freq2 then total valid pairs with this character will be min(freq1, freq2). The sum of this value for all the characters is the required answer.

How do you count common characters in a string in Python?

If you want to maintain a count of the number of characters in common, you should use collections. Counter instead of set .


1 Answers

Use set:

s = set("123 ABC")
t = set("135 AZ")
intersect = s & t # or s.intersection(t)
exclusion = s ^ t # or s.symmetric_difference(t)
a_minus_b = s - t # or s.difference(t)
b_minus_a = t - s # or t.difference(s)
like image 98
jason Avatar answered Sep 28 '22 12:09

jason