在Python Pangram检查中使用Set()
在本文中,我们将学习如何在Python3.x中确定字符串是否为“pangram”。或更早。一个pangram字符串包含英语字母列表中的每个字母。让我们看一下下图-
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
根据定义,完美的pangram会将“26个英文字母”中的每个字母恰好包含一次。本教程不包括“完美pangram”的概念。
现在,让我们看一下问题陈述和约束集。
问题陈述-给定字符串检查是否为Pangram。
约束条件
小写和大写被认为是相同的。
如上,在完美的Pangram情况下无需强迫。
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'.
相关数据结构
Set()和List()理解
先决条件
字符串和字符串操作
让我们快速浏览一下我们正在解决此问题的算法-
我们的首要任务是将完整的输入字符串转换为小写或大写形式。在这里,我使用Python3.x中数据类型为“string”的upper()方法进行大写转换。或更早。
现在,借助(str_input)函数,我们可以创建输入字符串中存在的所有不同元素的列表。
现在,我们将创建一个新列表“dist_list”,其中包含所有不同的字母,没有任何数字或特殊字符。
现在检查dist_list的长度是否为26。如果条件成立,则输入为Pangram,否则为非。
示例
# 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)结论
在本文中,我们学习了如何使用Python3.x判断字符串是否为Pangram。或更早。您可以实现相同的算法,以使用任何其他编程语言来创建Pangram检测器程序。