Python Set |检查给定的字符串是否为异形

给定一个由小写字符组成的字符串。任务是检查给定字符串中的一个字符是否为异形字符。异形词是一个单词、短语或句子,字母表中的任何字母都不会出现一次以上。

null

例如:

Input : S = "the big dwarf only jumps"
Output : Yes
Each alphabet in the string S is occurred
only once.

Input : S = "geeksforgeeks" 
Output : No
Since alphabet 'g', 'e', 'k', 's' occurred
more than once.

我们有解决这个问题的现有方案,请参考 检查给定字符串是否为异形 链接我们可以使用python快速解决这个问题 设置数据结构 .方法非常简单,

  1. 为了检查句子是否是异形词,我们只关心字母表,而不关心任何其他字符,所以我们把句子中出现的所有字母表分开。
  2. 将字母表列表转换为集合,因为集合包含唯一的值,如果集合的长度等于字母表的数量,这意味着每个字母表只出现一次,则句子是异形词,否则不是。

# Function to Check whether a given string is Heterogram or not
def heterogram( input ):
# separate out list of alphabets using list comprehension
# ord function returns ascii value of character
alphabets = [ ch for ch in input if ( ord (ch) > = ord ( 'a' ) and ord (ch) < = ord ( 'z' ) )]
# convert list of alphabets into set and
# compare lengths
if len ( set (alphabets)) = = len (alphabets):
print ( 'Yes' )
else :
print ( 'No' )
# Driver program
if __name__ = = "__main__" :
input = 'the big dwarf only jumps'
heterogram( input )


输出:

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