Python Set | Check whether a given string is Heterogram or not

Given a string S of lower case characters. The task is to check whether a the given string is Heterogram or not. A heterogram is a word, phrase, or sentence in which no letter of the alphabet occurs more than once.

Examples:

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.



We have existing solution for this problem please refer Check whether a given string is Heterogram or not link. We can solve this problem quickly in python using Set data structure. Approach is very simple,

  1. To check sentence is heterogram or not we only concern about alphabets not any other character, so we separate out list of all alphabets present in sentence.
  2. Convert list of alphabets into set because set contains unique values, if length of set is equal to number of alphabets that means each alphabet occured once then sentence is heterogram, otherwise not.
filter_none

edit
close

play_arrow

link
brightness_4
code

# 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)

chevron_right


Output:

Yes


My Personal Notes arrow_drop_up

Experienced Software Engineer with a demonstrated history of working in the information technology and services industry Skilled in Big Data technologies, Data Structures, Algorithm, Software Development, App Development, Databases, Python, Java, C, and WordPress

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.