Skip to content

Commit 8904af9

Browse files
realDuYuanChaogithub-actionscclauss
authored
Optimization for pangram string (#2473)
* optimization for pangram string * fixup! Format Python code with psf/black push * Update strings/check_pangram.py Co-authored-by: Christian Clauss <[email protected]> * updating DIRECTORY.md * Update strings/check_pangram.py Co-authored-by: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Co-authored-by: Christian Clauss <[email protected]>
1 parent 7446e69 commit 8904af9

File tree

1 file changed

+47
-5
lines changed

1 file changed

+47
-5
lines changed

strings/check_pangram.py

+47-5
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
1-
# Created by sarathkaul on 12/11/19
1+
"""
2+
wiki: https://en.wikipedia.org/wiki/Pangram
3+
"""
24

35

46
def check_pangram(
@@ -8,10 +10,16 @@ def check_pangram(
810
A Pangram String contains all the alphabets at least once.
911
>>> check_pangram("The quick brown fox jumps over the lazy dog")
1012
True
13+
>>> check_pangram("Waltz, bad nymph, for quick jigs vex.")
14+
True
15+
>>> check_pangram("Jived fox nymph grabs quick waltz.")
16+
True
1117
>>> check_pangram("My name is Unknown")
1218
False
1319
>>> check_pangram("The quick brown fox jumps over the la_y dog")
1420
False
21+
>>> check_pangram()
22+
True
1523
"""
1624
frequency = set()
1725
input_str = input_str.replace(
@@ -24,7 +32,41 @@ def check_pangram(
2432
return True if len(frequency) == 26 else False
2533

2634

27-
if __name__ == "main":
28-
check_str = "INPUT STRING"
29-
status = check_pangram(check_str)
30-
print(f"{check_str} is {'not ' if status else ''}a pangram string")
35+
def check_pangram_faster(
36+
input_str: str = "The quick brown fox jumps over the lazy dog",
37+
) -> bool:
38+
"""
39+
>>> check_pangram_faster("The quick brown fox jumps over the lazy dog")
40+
True
41+
>>> check_pangram("Waltz, bad nymph, for quick jigs vex.")
42+
True
43+
>>> check_pangram("Jived fox nymph grabs quick waltz.")
44+
True
45+
>>> check_pangram_faster("The quick brown fox jumps over the la_y dog")
46+
False
47+
>>> check_pangram_faster()
48+
True
49+
"""
50+
flag = [False] * 26
51+
for char in input_str:
52+
if char.islower():
53+
flag[ord(char) - ord("a")] = True
54+
return all(flag)
55+
56+
57+
def benchmark() -> None:
58+
"""
59+
Benchmark code comparing different version.
60+
"""
61+
from timeit import timeit
62+
63+
setup = "from __main__ import check_pangram, check_pangram_faster"
64+
print(timeit("check_pangram()", setup=setup))
65+
print(timeit("check_pangram_faster()", setup=setup))
66+
67+
68+
if __name__ == "__main__":
69+
import doctest
70+
71+
doctest.testmod()
72+
benchmark()

0 commit comments

Comments
 (0)