Length of the string Python

Question:

I need to check if a string is a Pangram (a sentence using every letter of the alphabet at least once) or not. Why do I get the right solution only when I use set. Why it is not working with string?

def checkIfPangram(sentence):
    return len(set(sentence)) == 26 # answer is True

print(checkIfPangram('thequickbrownfoxjumpsoverthelazydog'))

This solution does not work:

def checkIfPangram(sentence):
    return len(sentence) == 26

print(checkIfPangram('thequickbrownfoxjumpsoverthelazydog'))

Answer is not correct. With len(sentence) I get only False, but if I use set(sentence) then solution is correct.

Asked By: user531309

||

Answers:

In the first solution, you are using the set data structure to convert the sentence into a set of unique characters. The set data structure only allows unique elements, so by converting the sentence into a set, you are removing any duplicate characters. Then, you are checking if the length of the set is equal to 26, which is the number of unique letters in the English alphabet.

In the second solution, you are simply checking if the length of the sentence is equal to 26. This will only return True if the sentence has exactly 26 characters, regardless of whether those characters are all unique or not. This means that the second solution will not work for checking if a sentence is a pangram, because a pangram can have more than 26 characters if it includes duplicate letters.

Answered By: Mike

Declare a variable of type String.
Initialize the String variable to a non-null value.
Call the Java String length() method.
Hold the value of the String length in a variable for future use.

Answered By: Devansh -tiwari

If your sentence doesn’t include numbers, the len(set()) is correct because of property of set in python. As in mathematics, set in python can only hold unique values. by converting str to set, it adds every letter in the string one time only.

For ex. Assume we have a string – s1``. Both s1&s2are 26 char. long. But ins1there are two‘a’so yourlen(s1) == 26givesTruebutlen(set(s1)) == 26givesFalseas there are two occurrence of‘a’` and set only allows one which gives set of 25 items only!

Answered By: Prabhas Kumar

The sentence to be analysed might contain digits or whitespace and therefore cannot be a pangram even though the set of its characters might have a length of 26.

A more robust approach might be:

import string
def isPangram(sentence):
    return ''.join(sorted(set(sentence.lower()))) == string.ascii_lowercase
Answered By: Cobra
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.