Python集合|两个集合中的完整字符串对

两个字符串被称为完整字符串,如果在串联时,它们包含所有26个英文字母。例如,“abcdefghi”和“jklmnopqrstuvwxyz”是完整的,因为它们一起具有从“a”到“z”的所有字符。 我们分别得到两组大小n和m,我们需要找到将集合1中的每个字符串连接到集合2中的每个字符串的完整对数。

null

例如:

Input : set1[] = {"abcdefgh", "geeksforgeeks",
                 "lmnopqrst", "abc"}
        set2[] = {"ijklmnopqrstuvwxyz", 
                 "abcdefghijklmnopqrstuvwxyz", 
                 "defghijklmnopqrstuvwxyz"} 
Output : 7
The total complete pairs that are forming are:
"abcdefghijklmnopqrstuvwxyz"
"abcdefghabcdefghijklmnopqrstuvwxyz"
"abcdefghdefghijklmnopqrstuvwxyz"
"geeksforgeeksabcdefghijklmnopqrstuvwxyz"
"lmnopqrstabcdefghijklmnopqrstuvwxyz"
"abcabcdefghijklmnopqrstuvwxyz"
"abcdefghijklmnopqrstuvwxyz"

我们有解决这个问题的现有方案,请参考 两组字符串中的完整字符串对 链接我们可以使用python快速解决这个问题 设置数据结构 .方法非常简单,

  1. 考虑所有的字符串对,将它们串接起来,并将其转换成SET。
  2. 现在,将串联字符串中的所有字母逐个添加到集合中。由于集合包含唯一的值,所以若集合的长度等于26,则表示集合包含所有26个英文字母。

# Function to find pairs of complete strings
# in two sets of strings
def completePair(set1,set2):
# consider all pairs of string from
# set1 and set2
count = 0
for str1 in set1:
for str2 in set2:
result = str1 + str2
# push all alphabets of concatenated
# string into temporary set
tmpSet = set ([ch for ch in result if ( ord (ch)> = ord ( 'a' ) and ord (ch)< = ord ( 'z' ))])
if len (tmpSet) = = 26 :
count = count + 1
print (count)
# Driver program
if __name__ = = "__main__" :
set1 = [ 'abcdefgh' , 'geeksforgeeks' , 'lmnopqrst' , 'abc' ]
set2 = [ 'ijklmnopqrstuvwxyz' , 'abcdefghijklmnopqrstuvwxyz' , 'defghijklmnopqrstuvwxyz' ]
completePair(set1,set2)


输出:

7
© 版权声明
THE END
喜欢就支持一下吧
点赞8 分享