Python | Intersection of two lines

In Python, there are various ways in which we can cross two strings.

Method # 1: Naive method
Create an empty string and check for a new one a character common to both the string and its appendix. Hence the calculation of the new intersection line. This can be achieved with loops and if / else statements.

# Python3 demo code
# line intersection
# using the naive method

  
# string initialization

test_str1 = `GeeksforGeeks`

test_str2 = `Codefreaks`

  
# using a naive method for
# get line intersections

res = " "

for  i in test_str1:

if i in test_str2 and not i in res:

res + = i

 
# print intersection

print ( "String intersection is:" + res)

Output:

 String interse ction is: eksfor 

Method # 2: Using set () + intersection ()

First, both lines are converted to sets with set () and then intersection is done with intersection () . Returns a sorted set.

# Python3 demo code
# line intersection
# using set () + intersection ()

 
# line initialization

test_str1 = `GeeksforGeeks`

test_str2 = ` Codefreaks`

 
# using set () + intersection ( ) for
# get line intersections

res = set (test_str1) .interse ction (test_str2)

 
# print intersection

print ( "String intersection is:" + str (res))

Output:

 String intersection is: {`e`,` f`, `s`,` o`, `k`,` r`} 

Method # 3: Using join ()

join () performs a task similar to understanding lists in the case of lists. This encapsulates all the intersection logic and concatenates each element filtered through the intersection logic into one line, hence calculating the intersection. It converts the rows to a set, and then evaluates and processes them.

# Python3 demo code
# intersecting lines
# using join ()

  
# line initialization

test_str1 = `GeeksforGeeks`

test_str2 = `Codefreaks`

  
# using join () for
# get line intersections

res = `` .join ( sorted < code class = "plain"> ( set (test_str1) & amp; 

set (test_str2), key = test_str1.index))

 
# print intersection

print ( "String intersection is:" + str (res))

Output:

 String intersection is: eksfor