7.4 Code Practice: Question 1 Project Stem Python Gold Medals
Mastering the 7.4 Code Practice: Python Gold Medal Sorting for STEM Success
The “7.4 Code Practice: Question 1” from a typical Project STEM or similar computer science curriculum presents a foundational yet critical challenge: processing and sorting data. Often framed around Olympic medals, this problem tasks students with writing a Python program that reads a list of countries and their gold medal counts, then outputs a sorted ranking. This exercise is more than a simple sorting task; it is a deliberate step in building algorithmic thinking, a core competency in STEM education. Successfully navigating this problem solidifies your understanding of data structures, custom sorting logic, and clean code output—skills directly transferable to real-world data analysis and software development. This guide will deconstruct the problem, build the solution step-by-step, and explore the underlying concepts to ensure you not only write working code but truly understand the “why” behind each line.
Problem Statement: The Core Challenge
Before writing a single line of code, you must precisely understand the problem’s requirements. The standard formulation is as follows:
- Input: You will receive multiple lines of input. Each line contains a country’s name (a string without spaces) followed by an integer representing the number of gold medals that country has won. The input terminates with a line containing the single word
DONE. - Processing: Your program must collect all this data and sort the list of countries.
- Sorting Criteria: The primary sort key is the number of gold medals in descending order (highest to lowest). The secondary sort key, used to break ties, is the country name in ascending alphabetical order (A to Z).
- Output: Print the sorted list, one country per line, in the format:
Country: Gold Medals.
For example, given input:
USA 46
China 38
GreatBritain 27
Russia 19
Germany 17
DONE
The correct output must place the USA first (highest medals), followed by China, and so on, with countries having the same medal count sorted alphabetically.
Deconstructing the Challenge: A Step-by-Step Blueprint
Tackling any coding problem effectively begins with breaking it into discrete, manageable steps. This logical decomposition is a key STEM practice.
- Data Acquisition & Termination: Your program needs a loop that continuously reads input lines until it encounters the sentinel value
DONE. This loop is the gatekeeper for your data collection. - Data Parsing & Storage: Each valid input line (before
DONE) contains two pieces of information: a string (country) and an integer (medal count). You must split the line and convert the medal count from a string to an integer. This parsed data needs to be stored in a structured format. A list of tuples is ideal here, where each tuple is(country_name, medal_count). Tuples are immutable and perfectly suited for holding paired, related data. - Designing the Sort Logic: This is the algorithmic heart of the problem. Python’s built-in
sorted()function or thelist.sort()method are powerful, but they sort in ascending order by default. You need to:- Sort primarily by the medal count in reverse (descending).
- For countries with equal medal counts, sort by the country name normally (ascending).
The solution lies in providing a custom
keyfunction to the sorter. This function will return a tuple that Python can compare element-by-element. To get descending order for medals, we return the negative medal count (-medals), or we can use thereverse=Trueparameter strategically combined with a key that handles the secondary sort.
- Output Generation: After sorting, iterate through the sorted list and print each country and its medal count in the required format.
Algorithm Design & Implementation: Writing the Code
Let’s translate the blueprint into clean, commented Python code. We will use the approach of a custom key function that returns a tuple (-medals, country). This tuple leverages Python’s ability to compare tuples lexicographically: it
... it compares the first element (-medals) first. Since sorting is ascending by default, using the negative medal count effectively reverses the order for the primary key (higher medal counts become lower negative numbers). If two countries have the same -medals (i.e., the same original medal count), Python then compares the second element (country) in standard ascending alphabetical order.
Here is the complete implementation following the blueprint:
def main():
data = []
while True:
line = input().strip()
if line == "DONE":
break
parts = line.split()
country = parts[0]
medals = int(parts[1])
data.append((country, medals))
# Sort by: primary key = negative medals (descending), secondary key = country (ascending)
sorted_data = sorted(data, key=lambda x: (-x[1], x[0]))
for country, medals in sorted_data:
print(f"{country}: {medals}")
if __name__ == "__main__":
main()
This code efficiently collects the input, applies the custom sort logic via a lambda function that returns the tuple (-medals, country), and prints the results in the required format. The use of a tuple as the sort key is a powerful Python idiom that elegantly handles multi-level sorting criteria without complex conditional logic.
Conclusion
This exercise illustrates a fundamental problem-solving pattern in programming: decompose, design, implement. By first breaking the problem into clear steps—input handling, data structuring, sorting logic, and output—we avoid overwhelm and create a logical roadmap. The core technical insight was leveraging Python’s tuple comparison to implement a multi-key sort concisely. This approach of using a composite key (often with negation for descending order) is widely applicable, from sorting complex records to prioritizing tasks. Mastering such patterns transforms daunting challenges into manageable, repeatable processes, building the analytical foundation necessary for tackling larger, real-world software problems.
Latest Posts
Latest Posts
-
Which Of The Following Studies Would Need Irb Approval
Mar 24, 2026
-
Ap Lit Unit 4 Progress Check Mcq
Mar 24, 2026
-
Absorption And Secretion Occur In The Of The Nephron
Mar 24, 2026
-
Reliability Is Defined By The Text As
Mar 24, 2026
-
Studysync Grade 10 Answer Key Pdf
Mar 24, 2026