Using Set() in Python Pangram Checking

PythonServer Side ProgrammingProgramming

In this article, we will learn how to determine whether a string is “pangram” or not in Python 3.x. Or earlier. A pangram string contains every letter in the list of English language alphabets . Let us look at the illustration below −

Provided Input: str = 'This is the python blog on Tutorial point'
Desired Output: No
Provided Input : str='I want to contribute to a 'dxyzwuvghlkfmq' open source project'
Desired Output: Yes

By definition, a perfect pangram includes every letter of the ‘26 English alphabets’ exactly once. This tutorial doesn’t include the concept of ‘perfect pangram’.

Now Let’s look at the problem statement and set of constraints.

Problem Statement − Given a string check whether it is Pangram or not.

Constraints

  1. Lowercase and Uppercase are considered the same.
  2. No compulsion on the perfect Pangram case as discussed above.
Input: First line of input contains the test string ‘str_input ’
Output: Print 'String is a Pangram' if conditions evaluate to be true,
otherwise it displays 'String is not a Pangram'.

Related Data Structure

Set() & List() Comprehension

Prerequisite

String & String Operations

Let us quickly go through the algorithm we are implementing in this problem −

  1. Our first task is to convert the complete input string in lowercase or uppercase. Here I am using uppercase conversion using upper() method of data type “string” in Python 3.x. Or earlier.

  2. Now with the help of (str_input) function, we can create a list of all distinct elements present in the input string.

  3. Now we will make a new list “dist_list” which contain all distinct alphabets without any number or special character.

  4. Now check whether the length of the dist_list is 26 or not. If the condition holds true, the input is a Pangram otherwise not.

Example

# user-defined function to check Pangram
def check_pangram(input):
   # convert input string into uppercase
   str_input = str_input.upper()

   # convert input string into Set()
   # a list of distinct elements will be formed.
   str_input = set(str_input)

# separate out alphabets from numbers and special characters
# ord(ch) returns the ASCII value of the character

dist_list = [ char for char in str_input if ord(char) in range(ord('a'), ord('z')+1)]
   if len(dist_list) == 26:
      return 'String is a Pangram'
   else:
      return 'String is not a Pangram'

# Executable main function
if __name__ == "__main__":
   str_input = input()
   print check_pangram(str_input)

Conclusion

In this article, we learnt how to figure out if a string is Pangram or not using Python 3.x. Or earlier. You can implement the same algorithm to create a pangram detector program in any other programming language.

raja
Published on 08-Jul-2019 12:45:37
Advertisements