Python - Intersectiing strings

前端 未结 6 613
北海茫月
北海茫月 2021-01-18 08:26

Trying to write a for function that takes two strings and returns the characters that intersect in the order that they appear in the first string.

Here\'s what I tri

6条回答
  •  滥情空心
    2021-01-18 08:42

    Check for occurances the other way around to get the order under control, and don't emit characters you've already emitted:

    def strIntersection(s1, s2):
      out = ""
      for c in s1:
        if c in s2 and not c in out:
          out += c
      return out
    

    Sure you could re-write it to be a list comprehension, but I find this easier to understand.

    For your test data, we get:

    >>> strIntersection('asdfasdfasfd' , 'qazwsxedc')
    'asd'
    

提交回复
热议问题