TheAlgorithms-Python
95 строк · 2.7 Кб
1"""
2wiki: https://en.wikipedia.org/wiki/Pangram
3"""
4
5
6def is_pangram(7input_str: str = "The quick brown fox jumps over the lazy dog",8) -> bool:9"""10A Pangram String contains all the alphabets at least once.
11>>> is_pangram("The quick brown fox jumps over the lazy dog")
12True
13>>> is_pangram("Waltz, bad nymph, for quick jigs vex.")
14True
15>>> is_pangram("Jived fox nymph grabs quick waltz.")
16True
17>>> is_pangram("My name is Unknown")
18False
19>>> is_pangram("The quick brown fox jumps over the la_y dog")
20False
21>>> is_pangram()
22True
23"""
24# Declare frequency as a set to have unique occurrences of letters25frequency = set()26
27# Replace all the whitespace in our sentence28input_str = input_str.replace(" ", "")29for alpha in input_str:30if "a" <= alpha.lower() <= "z":31frequency.add(alpha.lower())32return len(frequency) == 2633
34
35def is_pangram_faster(36input_str: str = "The quick brown fox jumps over the lazy dog",37) -> bool:38"""39>>> is_pangram_faster("The quick brown fox jumps over the lazy dog")
40True
41>>> is_pangram_faster("Waltz, bad nymph, for quick jigs vex.")
42True
43>>> is_pangram_faster("Jived fox nymph grabs quick waltz.")
44True
45>>> is_pangram_faster("The quick brown fox jumps over the la_y dog")
46False
47>>> is_pangram_faster()
48True
49"""
50flag = [False] * 2651for char in input_str:52if char.islower():53flag[ord(char) - 97] = True54elif char.isupper():55flag[ord(char) - 65] = True56return all(flag)57
58
59def is_pangram_fastest(60input_str: str = "The quick brown fox jumps over the lazy dog",61) -> bool:62"""63>>> is_pangram_fastest("The quick brown fox jumps over the lazy dog")
64True
65>>> is_pangram_fastest("Waltz, bad nymph, for quick jigs vex.")
66True
67>>> is_pangram_fastest("Jived fox nymph grabs quick waltz.")
68True
69>>> is_pangram_fastest("The quick brown fox jumps over the la_y dog")
70False
71>>> is_pangram_fastest()
72True
73"""
74return len({char for char in input_str.lower() if char.isalpha()}) == 2675
76
77def benchmark() -> None:78"""79Benchmark code comparing different version.
80"""
81from timeit import timeit82
83setup = "from __main__ import is_pangram, is_pangram_faster, is_pangram_fastest"84print(timeit("is_pangram()", setup=setup))85print(timeit("is_pangram_faster()", setup=setup))86print(timeit("is_pangram_fastest()", setup=setup))87# 5.348480500048026, 2.6477354579837993, 1.847039583022706288# 5.036091582966037, 2.644472333951853, 1.886952875065617389
90
91if __name__ == "__main__":92import doctest93
94doctest.testmod()95benchmark()96