Python, Concept by Concept › Algorithm Challenge
Problems: Algorithm Challenge
Bring together your skills from Python, Concept by Concept in eleven precise algorithm problems. Build and check one problem at a time, using every worked sample before you move on.
Milestone 1
Number algorithms
Problem 1
A number lab needs the prime at a requested position.
Specification: Define nth_prime(k) to return the k-th prime, where k is 1-indexed. Use a while counter over candidate numbers. Test each candidate with the inner loop for d in range(2, candidate):, and break when candidate % d == 0; the empty range makes 2 prime.
Worked sample:
nth_prime(1) -> 2
nth_prime(5) -> 11
nth_prime(10) -> 29
How this is checked: Checked by tests that run your function nth_prime.
Problem 2
A display needs the digits of a non-negative number turned around.
Specification: Define reverse_digits(n) to reverse the digits of a non-negative integer arithmetically. Start rev at 0, then repeat rev = rev * 10 + n % 10 and n = n // 10 with a while loop. Return rev; make sure an input of 0 returns 0.
Worked sample:
reverse_digits(1234) -> 4321
reverse_digits(1200) -> 21
reverse_digits(0) -> 0
How this is checked: Checked by tests that run your function reverse_digits.
Milestone 2
Lists and searching
Problem 3
A scoreboard needs its three strongest results in order.
Specification: Define top_three(scores) for a list containing at least three values. Use sorted(scores) to make an ascending list, then read its last three values by index in reverse order — for example, if ordered = sorted(scores), then ordered[len(ordered) - 1] is the largest — and return them as a descending list. Do not use .copy() or [::-1].
Worked sample:
top_three([4,9,1,7,3]) -> [9,7,4]
top_three([5,5,2,8]) -> [8,5,5]
top_three([10,20,30]) -> [30,20,10]
How this is checked: Checked by tests that run your function top_three.
Problem 4
Two sorted arrival lists need to become one sorted line.
Specification: Define merge_sorted(a, b) to merge two ascending lists into one ascending list. Use a two-index walk with while i < len(a) and j < len(b), append the smaller current value, and then drain each remaining list with its own while loop.
Worked sample:
merge_sorted([1,4,6],[2,3,5]) -> [1,2,3,4,5,6]
merge_sorted([],[2,9]) -> [2,9]
merge_sorted([3,8,9],[]) -> [3,8,9]
How this is checked: Checked by tests that run your function merge_sorted.
Problem 5
A catalog search should discard half of its remaining choices at every step.
Specification: Define binary_search(nums, target) for a sorted list of distinct values. Return the index of target, or -1 when it is absent. Use while lo <= hi and calculate mid = (lo + hi) // 2 on every pass.
Worked sample:
binary_search([1,3,5,7,9],7) -> 3
binary_search([1,3,5,7,9],4) -> -1
binary_search([2,4,6,8,10,12],2) -> 0
How this is checked: Checked by tests that run your function binary_search.
Milestone 3
Text, tallies, and files
Problem 6
A text analyzer needs to count matches even when two matches overlap.
Specification: Define count_substring(text, part) to count overlapping, case-sensitive occurrences of part. Walk for i in range(len(text) - len(part) + 1): and compare text[i:i+len(part)] with part at every position.
Worked sample:
count_substring("cocoon","co") -> 2
count_substring("aaaa","aa") -> 3
count_substring("possession","ss") -> 2
How this is checked: Checked by tests that run your function count_substring.
Problem 7
A field notebook needs a reusable count of the words saved in a file.
Specification: Define word_counts_from_file(path) to READ a saved file of words and return their counts — the function itself only reads, it never writes. Open path with with open(path, "r"), loop with for line in f:, clean each word with .strip(), tally it in a dictionary with .get, and return the dictionary. For a self-contained test, first write the fixed words ["fern","moss","fern","larch","moss","fern"] one per line to path with an f-string (f.write(f"{word}\n")), then call the function. Use p7_words.txt for the sample.
Worked sample:
writing ["fern","moss","fern","larch","moss","fern"] to "p7_words.txt"
word_counts_from_file("p7_words.txt") -> {"fern":3,"moss":2,"larch":1}
How this is checked: You check this one yourself, against the list below.
The site cannot check this one. Run your program, then tick each item below when your work does it.
Problem 8
A word report needs the single most frequent entry in a saved list.
Specification: Define most_common_word(path) to READ a saved file of words and return the single word with the highest count — the function only reads. Tally the words with .strip() and .get, then find the best by iterating with the single-variable form for key in counts: (do not use .items()). For a self-contained test, first write the fixed words ["kite","yoyo","kite","kite","yoyo"] one per f-string line to path, then call the function. Use p8_words.txt for the sample.
Worked sample:
writing ["kite","yoyo","kite","kite","yoyo"] to "p8_words.txt"
most_common_word("p8_words.txt") -> "kite"
How this is checked: You check this one yourself, against the list below.
The site cannot check this one. Run your program, then tick each item below when your work does it.
Problem 9
A sorter needs to split numbers into even and odd groups without changing their order.
Specification: Define group_by_parity(nums) to return {"even": [...], "odd": [...]} while preserving the input order inside each list. Append n to the even list when n % 2 == 0, and otherwise append it to the odd list; 0 is even.
Worked sample:
group_by_parity([1,2,3,4]) -> {"even":[2,4],"odd":[1,3]}
group_by_parity([0,7,10]) -> {"even":[0,10],"odd":[7]}
group_by_parity([]) -> {"even":[],"odd":[]}
How this is checked: Checked by tests that run your function group_by_parity.
Milestone 4
Objects and pipelines
Problem 10
A live counter needs to remember every value and summarize the collection.
Specification: Define class RunningTally. Its __init__(self) starts an empty list attribute. add(self, value) appends the value and returns the number of stored values so far. total(self) returns sum(...), highest(self) returns max(...), and describe(self) returns the f-string f"{count} values, total {total}, highest {highest}". Call add at least once before highest or describe.
Worked sample:
t = RunningTally()
t.add(5) -> 1
t.add(9) -> 2
t.add(0) -> 3
t.total() -> 14
t.highest() -> 9
t.describe() -> "3 values, total 14, highest 9"
How this is checked: You check this one yourself, against the list below.
The site cannot check this one. Run your program, then tick each item below when your work does it.
Problem 11
A data pipeline needs to turn saved values into saved running totals.
Specification: Define running_totals_to_file(in_path, out_path) to READ integers from in_path (one per line, with int(line.strip())), accumulate a running total, WRITE each running total as an f-string line to out_path, and return the list of running totals. The function reads its input file and writes its output file; it does not create the input. For a self-contained test, first write the fixed integers [5,3,2] one per f-string line to in_path, then call the function. Use p11_in.txt and p11_out.txt for the sample.
Worked sample:
writing [5,3,2] to "p11_in.txt"
running_totals_to_file("p11_in.txt", "p11_out.txt") -> [5,8,10]
p11_out.txt -> "5\n8\n10\n"
How this is checked: You check this one yourself, against the list below.
The site cannot check this one. Run your program, then tick each item below when your work does it.
Make it yours
After all eleven problems work, choose one extension.
- Invent one fresh worked sample for a function and predict its exact return value before running it.
- Feed the list returned by
running_totals_to_fileintotop_threewhen it contains at least three totals. - Add a
lowest(self)method toRunningTallythat returnsmin(...)after at least one value has been added.
Requirements checklist
- [ ] I defined
nth_prime(k),reverse_digits(n),top_three(scores),merge_sorted(a, b),binary_search(nums, target),count_substring(text, part),word_counts_from_file(path),most_common_word(path),group_by_parity(nums), classRunningTallywith__init__(self),add(self, value),total(self),highest(self), anddescribe(self), andrunning_totals_to_file(in_path, out_path)with the exact names and signatures. - [ ] I reproduced every worked sample and its exact output.
- [ ] My file problems are self-contained at the cell level: the cell writes the known input file first, then calls the function (
word_counts_from_fileandmost_common_wordonly read;running_totals_to_filereads its input file and writes its output file). For the worked samples this usesp7_words.txt,p8_words.txt,p11_in.txt, andp11_out.txt.