Python - Intersectiing strings

前端 未结 6 550
北海茫月
北海茫月 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:28
    def str_intersection(str1, str2):
        common_letters = set(str1) & set(str2)
        str3 = ''
        for c in str1:
            if (c in common_letters) and (c not in str3):
                str3 += c
        return str3
    
    0 讨论(0)
  • 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'
    
    0 讨论(0)
  • 2021-01-18 08:43

    It looks like your current script should do it if you fix the typo on the fourth line:

    str3 = str3.join(i for i in str1 if i in str2 not in str3)
    

    should be

    str3 = str3.join(i for i in str1 if i in str2 and i not in str3)
    

    I wouldn't recommend using a set for this simpy because they don't guarantee order. Your script is also likely to be faster.

    0 讨论(0)
  • 2021-01-18 08:48

    You want a string consisting of the unique characters that are common to str1 and str2, in the order they appear in str1.

    Uniqueness and commonality imply set operations: that is, we're looking for the set of characters that appear in both str1 and str2. A set is fundamentally unordered, but we can re-order the data by sorting the characters according to their "index" of first occurrence in str1. Then it's a simple matter of creating a string from the sorted sequence.

    Putting it all together, we get:

    ''.join(sorted(set(str1) & set(str2), key = str1.index))
    
    0 讨论(0)
  • 2021-01-18 08:52

    You can use python sets http://docs.python.org/library/stdtypes.html#set to do this, like so:

    >>> set("asdfasdfasfd") & set("qazwsxedc")
    set(['a', 's', 'd'])
    
    0 讨论(0)
  • 2021-01-18 08:54

    easiest is to use sets in python

    >>> a='asdfasdfasfd'
    >>> b='qazwsxedc'
    >>> set(a).intersection(b)
    set(['a', 's', 'd'])
    
    0 讨论(0)
提交回复
热议问题