Python 程式檢查給定的字串是否異構詞


這裡給定一個字串,我們的任務是檢查給定的字串是否為異構詞。

異構詞檢查的含義是,一個單詞、短語或句子中沒有一個字母出現超過一次。異構詞可以與全異序詞區分開來,後者使用所有字母表中的字母。

示例

字串是 abc def ghi

This is Heterogram (no alphabet repeated)

字串是 abc bcd dfh

This is not Heterogram. (b,c,d are repeated)

演算法

Step 1: first we separate out list of all alphabets present in sentence.
Step 2: Convert list of alphabets into set because set contains unique values.
Step 3: if length of set is equal to number of alphabets that means each alphabet occurred once then sentence is heterogram, otherwise not.

示例程式碼

def stringheterogram(s, n):
   hash = [0] * 26
   for i in range(n):
   if s[i] != ' ':
      if hash[ord(s[i]) - ord('a')] == 0:
      hash[ord(s[i]) - ord('a')] = 1
   else:
   return False
   return True

   # Driven Code
   s = input("Enter the String ::>")
   n = len(s)
print(s,"This string is Heterogram" if stringheterogram(s, n) else "This string is not Heterogram")

輸出

Enter the String ::> asd fgh jkl
asd fgh jkl this string is Heterogram

Enter the String ::>asdf asryy
asdf asryy This string is not Heterogram

更新時間:2020 年 6 月 23 日

超過 1K 瀏覽量

開啟你的職業

完成課程即可獲得認證

開始學習
廣告
© . All rights reserved.