-
-
Notifications
You must be signed in to change notification settings - Fork 48
West Midlands | 26 March SDC | Iswat Bello | Sprint 2 | Improve code with precomputing #203
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Iswanna
wants to merge
3
commits into
CodeYourFuture:main
Choose a base branch
from
Iswanna:improve-code-with-precomputing
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,46 @@ | ||
| # Changes Made: Optimization via Pre-computing | ||
|
|
||
| ## Overview | ||
| These changes apply the strategy of **Pre-computing**: doing work upfront (like sorting or indexing) to make the primary search or calculation significantly faster. This allowed both algorithms to scale from small examples to datasets containing millions of items. | ||
|
|
||
| --- | ||
|
|
||
| ## 1. Longest Common Prefix Optimization (`common_prefix.py`) | ||
|
|
||
| ### The Problem | ||
| The original implementation used a nested loop to compare every string in a list against every other string. | ||
| - **Original Complexity**: $O(N^2)$. | ||
| - **The Bottleneck**: With 1,000,000 strings, the code would perform roughly 1 trillion comparisons, causing it to hang indefinitely. | ||
|
|
||
| ### The Solution: "Sort Before Search" | ||
| I implemented alphabetical sorting as a pre-computation step. | ||
| - **Why it works**: In a sorted list, the strings that share the longest common prefixes are mathematically guaranteed to be **neighbors**. | ||
| - **The Change**: By sorting the list first, I replaced the nested loop with a single pass that only compares each string to the one immediately following it. | ||
| - **Improved Complexity**: $O(N \log N)$ for the sort + $O(N)$ for the single-pass search. | ||
| - **Legacy Retention**: Kept the original `find_common_prefix` helper function and variable names (`longest`, `string`, `other_string`) to maintain code continuity. | ||
|
|
||
| --- | ||
|
|
||
| ## 2. Count Letters Optimization (`count_letters.py`) | ||
|
|
||
| ### The Problem | ||
| The original code contained a "hidden loop" inside a string iteration. | ||
| - **Original Complexity**: $O(N^2)$. | ||
| - **The Bottleneck**: The check `if letter.lower() not in s` required the computer to scan the entire string `s` for every character. On a 10-million-character string, this resulted in an impossible amount of work. | ||
|
|
||
| ### The Solution: "Sets for Instant Lookups" | ||
| I introduced a pre-computed **Set** to handle character lookups. | ||
| - **Why it works**: Searching for an item in a Python `set` (a hash table) takes **O(1) constant time**, whereas searching a `string` takes **O(N) linear time**. | ||
| - **The Change**: I converted the string `s` into a set (`chars_in_string`) at the start of the function. This one-time $O(N)$ operation transformed the inner search from a slow scan into an instant lookup. | ||
| - **Improved Complexity**: $O(N)$ — one pass to build the set, and one pass to loop through the string. | ||
| - **Legacy Retention**: Preserved the original loop structure (`for letter in s`), the `is_upper_case` helper, and the `only_upper` variable name. | ||
|
|
||
| --- | ||
|
|
||
| ## 3. Technical Trade-offs: Space vs. Time | ||
| Both tasks are classic examples of the **Space-vs-Time trade-off**: | ||
|
|
||
| 1. **Memory (Space)**: We used extra memory to store a sorted version of the list (Task 5) and a set of unique characters (Task 6). | ||
| 2. **Speed (Time)**: By "spending" this memory, we drastically reduced the number of CPU operations required. | ||
|
|
||
| **Result**: Operations that previously would have taken hours now complete in milliseconds, representing a massive gain in software scalability and performance. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
13 changes: 11 additions & 2 deletions
13
Sprint-2/improve_with_precomputing/count_letters/count_letters.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,14 +1,23 @@ | ||
| def count_letters(s: str) -> int: | ||
| """ | ||
| count_letters returns the number of letters which only occur in upper case in the passed string. | ||
|
|
||
| Optimized via Pre-computing: We convert the string to a set upfront to make | ||
| the 'not in' check a constant-time operation. | ||
| """ | ||
| # PRE-COMPUTING: Create a set of all unique characters in the string. | ||
| # Searching a set takes O(1) time, while searching a string takes O(N) time. | ||
| chars_in_string = set(s) | ||
|
|
||
| only_upper = set() | ||
| # LEGACY LOOP: Iterate through the string as originally designed. | ||
| for letter in s: | ||
| if is_upper_case(letter): | ||
| if letter.lower() not in s: | ||
| # OPTIMIZATION: Check against the pre-computed set instead of the full string 's'. | ||
| if letter.lower() not in chars_in_string: | ||
| only_upper.add(letter) | ||
| return len(only_upper) | ||
|
|
||
|
|
||
| def is_upper_case(letter: str) -> bool: | ||
| return letter == letter.upper() | ||
| return letter == letter.upper() |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This sorting step is the heart of your optimisation and it's spot-on. One subtle thing worth noticing, though:
strings.sort()sorts the list in place — it reorders the very list the caller handed you. The original function only ever read the list, so whoever called it could rely on their list staying in its original order afterwards; with.sort(), it silently comes back rearranged.For a test that just checks the return value it makes no difference — but imagine a caller who does something else with their list right after calling you. Python gives you a close cousin of
.sort()that returns a new sorted list instead of changing the original in place — do you know which one? What would swapping to it cost you here, and what would it protect the caller from?Your result is correct — this is just about being a considerate houseguest with data you don't own.