Skip to content

Commit f591dda

Browse files
Optimize common_prefix and count_letters with precomputing
1 parent de683df commit f591dda

File tree

2 files changed

+11
-13
lines changed

2 files changed

+11
-13
lines changed

Sprint-2/improve_with_precomputing/common_prefix/common_prefix.py

Lines changed: 8 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -2,17 +2,16 @@
22

33

44
def find_longest_common_prefix(strings: List[str]):
5-
"""
6-
find_longest_common_prefix returns the longest string common at the start of any two strings in the passed list.
5+
6+
if len(strings) < 2:
7+
return ""
78

8-
In the event that an empty list, a list containing one string, or a list of strings with no common prefixes is passed, the empty string will be returned.
9-
"""
9+
sorted_strings = sorted(strings)
1010
longest = ""
11-
for string_index, string in enumerate(strings):
12-
for other_string in strings[string_index+1:]:
13-
common = find_common_prefix(string, other_string)
14-
if len(common) > len(longest):
15-
longest = common
11+
for index in range(len(sorted_strings) - 1):
12+
common = find_common_prefix(sorted_strings[index], sorted_strings[index + 1])
13+
if len(common) > len(longest):
14+
longest = common
1615
return longest
1716

1817

Sprint-2/improve_with_precomputing/count_letters/count_letters.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,10 @@
11
def count_letters(s: str) -> int:
2-
"""
3-
count_letters returns the number of letters which only occur in upper case in the passed string.
4-
"""
2+
3+
lower_letters = {letter for letter in s if letter.islower()}
54
only_upper = set()
65
for letter in s:
76
if is_upper_case(letter):
8-
if letter.lower() not in s:
7+
if letter.lower() not in lower_letters:
98
only_upper.add(letter)
109
return len(only_upper)
1110

0 commit comments

Comments
 (0)