Python | Common words among strings of a tuple



Method # 1: Using join () + set () + & amp; operator + split ()
A combination of the above functions can be used to accomplish this specific task. In this, we first convert each tuple to a set and then perform the intersection of the element words separated by split () . The last step — join all common elements using join () .

# Python3 code to demonstrate how it works
# Common words among tuple lines
# Using join () + set () + & amp; operator + split ()

 
# Tuple initialization

test_tup = ( ` gfg is best` , `gfg is for geeks` , `gfg is for all` )

  
# print the original tuple

print ( "The original tuple is:" + str (test_tup))

 
# Common words among the lines of a tuple
# Using join () + set () + & amp; operator + split ()

res = "," . join ( sorted ( set (test_tup [ 0 ]. split ()) & amp;

set (test_tup [ 1 ]. split ()) & amp;

set (test_tup [ 2 ]. split ())))

 
# print result

print ( "Common words among tuple are:" res)

Exit:

 The original tuple is: (`gfg is best`,` gfg is for geeks`, `gfg is for all`) Common words among tuple are: gfg, is 

Method # 2: Using map () + reduce () + lambda
A combination of the above methods can also be used to accomplish this particular tasks. In this case, we simply combine all the elements of the tuple to check for common elements using lambda and reduce () . The advantage of this method is that it can easily work with a tuple of more than countable elements. Only works with Python3.

# Python3 code to demonstrate how it works
# Common words among strings tuple
# Using map () + decrease () + lambda

 
# Tuple initialization

test_tup = ( `gfg is best` , `gfg is for geeks` , ` gfg is for all` )

 
# print original tuple

print ( "The origina l tuple is: " + str (test_tup))

 
# Common words among tuple lines
# Map usage () + decrease () + lambda

res = "," . join ( reduce ( lambda i, j: i & amp; j, 

map ( lambda x: set (x.split ()), test_tup)))

 
# result print

print ( "Common words among tuple are: " + res)

Output:

 The original tuple is: (`gfg is best`,` gfg is for geeks`, `gfg is for all`) Common words among tuple are: gfg, is