1

I'm currently doing one of the code fight's challenges, basically the challenge is to find the number of common characters between two strings. I came up with the solution below. I already passed the challenge, but I cannot figure out why I would have to iterate over the list twice and also not in every case. Thanks in advance for any explanations.

        strings = [
            ["aabcc", "adcaa"],
            ["abca", "xyzbac"],
            ["assssbs", "aasaaaa"],
            ["zzzzzz", "zzz"],
            ["abcdefghxyzttw", "hgfedcbaabcwwt"] #<-- the strings failing with one iteration
        ]


        def commonCharacterCount(s1, s2):
            s1, s2 = sorted(list(s1)), sorted(list(s2))
            matches = []

            def matched(i):
                matches.append(i)
                s1.remove(i)
                s2.remove(i)

            [matched(i) for i in s1 if i in s2]
            [matched(i) for i in s2 if i in s1]
            [matched(i) for i in s1 if i in s2] #<-- Second for loop to find f

            return len(matches)


        def test():
            for i in strings:
                commonCharacterCount(i[0], i[1])
            return


        test() 
doughboy
  • 61
  • 7

1 Answers1

1

You simply try this

lis=["abcdef","abcdv"]

match=[i for i in lis[0]if i in lis[1]]

It gives out put

['a', 'b', 'c', 'd']

Edit

For only one time check

>>> a
['abcc', 'abbbc']
>>> check0=list(a[0])
>>> check1=list(a[1])
>>> match=list()
>>> for i in check0:
    if i in check1:
        check1.remove(i)
        match.append(i)

Out Put

['a', 'b', 'c']

Artier
  • 1,648
  • 2
  • 8
  • 22
  • Yeah but this won't handle duplicate letters ["aabcc", "adcaa"] would give output of ['a', 'a', 'c', 'c'] although c is only matched once, that is why I was removing the elements as I iterated over them. The answer is in one of the links unutbu posted. What I found out is the index is, the index is changing as I remove items. I'm coming up with solution now I'll post it as answer when I'm done but thanks. – doughboy Jan 26 '18 at 16:41
  • I have update my answer check now – Artier Jan 26 '18 at 18:29