Open In App

Python set to check if string is pangram

Given a string, check if the given string is a pangram or not.

Examples: 



Input : The quick brown fox jumps over the lazy dog
Output : The string is a pangram

Input : geeks for geeks
Output : The string is not pangram

A normal way would have been to use frequency table and check if all elements were present or not. But using import ascii_lowercase as asc_lower we import all the lower characters in set and all characters of string in another set. In the function, two sets are formed- one for all lower case letters and one for the letters in the string. The two sets are subtracted and if it is an empty set, the string is a pangram.

Below is Python implementation of the above approach: 






# import from string all ascii_lowercase and asc_lower
from string import ascii_lowercase as asc_lower
 
# function to check if all elements are present or not
def check(s):
    return set(asc_lower) - set(s.lower()) == set([])
     
# driver code
string ="The quick brown fox jumps over the lazy dog"
if(check(string)== True):
    print("The string is a pangram")
else:
    print("The string isn't a pangram")

Output
The string is a pangram

Time Complexity: O(n)
Auxiliary Space: O(1) 

Method #2: Using lower(),replace(),list(),set(),sort() and join() methods




# function to check if all elements are present or not
 
string ="The quick brown fox jumps over the lazy dog"
string=string.replace(" ","")
string=string.lower()
x=list(set(string))
x.sort()
x="".join(x)
alphabets="abcdefghijklmnopqrstuvwxyz"
if(x==alphabets):
    print("The string is a pangram")
else:
    print("The string isn't a pangram")

Output
The string is a pangram

Time Complexity : O(N logN)
Auxiliary Space : O(N)

Method #3 : Using lower(),replace(),len() methods and for loop

Approach

  1. Convert the given string to lowercase and remove all spaces
  2. Check whether all the alphabets are present in given string by incrementing count variable and for loop
  3. If count is equal to 26(number of alphabets) display The string is a pangram
  4. If not display The string isn’t a pangram




# function to check if all elements are present or not
 
string ="The quick brown fox jumps over the lazy dog"
string=string.replace(" ","")
string=string.lower()
alphabets="abcdefghijklmnopqrstuvwxyz"
c=0
for i in alphabets:
    if i in string:
        c+=1
if(c==len(alphabets)):
    print("The string is a pangram")
else:
    print("The string isn't a pangram")

Output
The string is a pangram

Time Complexity : O(N) N – total number of alphabets

Auxiliary Space : O(1) 


Article Tags :