Skip to content

Commit 01e2c72

Browse files
committed
Refactor common_prefix and count_letter functions with precomputing.
1 parent e718fb4 commit 01e2c72

File tree

2 files changed

+25
-10
lines changed

2 files changed

+25
-10
lines changed

Sprint-2/improve_with_precomputing/common_prefix/common_prefix.py

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,12 +7,17 @@ def find_longest_common_prefix(strings: List[str]):
77
88
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.
99
"""
10+
if len(strings) < 2:
11+
return ""
12+
# reducing comparison by sorting places strings with similar prefixes next to each other...
13+
strings.sort()
14+
1015
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
16+
for i in range(len(strings) - 1):
17+
# compares only adjacent strings after sorting
18+
common = find_common_prefix(strings[i], strings[i + 1])
19+
if len(common) > len(longest):
20+
longest = common
1621
return longest
1722

1823

Sprint-2/improve_with_precomputing/count_letters/count_letters.py

Lines changed: 15 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,23 @@ def count_letters(s: str) -> int:
22
"""
33
count_letters returns the number of letters which only occur in upper case in the passed string.
44
"""
5-
only_upper = set()
5+
lower_case = set()
6+
upper_case = set()
7+
8+
# collects lowercase and uppercase letters
69
for letter in s:
7-
if is_upper_case(letter):
8-
if letter.lower() not in s:
9-
only_upper.add(letter)
10-
return len(only_upper)
10+
if letter.islower():
11+
lower_case.add(letter)
12+
elif is_upper_case(letter):
13+
upper_case.add(letter)
14+
15+
# counts uppercase letters not in lowercase
16+
count = 0
17+
for letter in upper_case:
18+
if letter.lower() not in lower_case:
19+
count += 1
1120

21+
return count
1222

1323
def is_upper_case(letter: str) -> bool:
1424
return letter == letter.upper()

0 commit comments

Comments
 (0)