Python数组实现高效硬币找零程序:优化方案咨询(CS教学场景)
Optimizing Your Python Coin Change Program
Hey there! As a computer science educator, I totally get wanting a clean, efficient implementation that also works as a great teaching example for your students. Let's walk through how to refine your current code and make it more scalable, concise, and performant.
First, let's break down the key limitations of your current code:
- Hardcoded coin variables: Separate variables like
fifty,twentymean you’d have to rewrite large chunks of code if you ever adjust the coin denominations (e.g., adding a 25p coin). - Inefficient loop logic: Subtracting one coin at a time leads to unnecessary iterations, especially for large amounts.
- Redundant condition checks: Multiple
ifstatements repeat similar logic, violating the DRY (Don't Repeat Yourself) principle.
Here's a streamlined, efficient implementation using the greedy algorithm (perfect for your coin set):
The greedy approach works flawlessly here because your denominations are canonical (each coin is a divisor of larger ones, so choosing the largest possible coin every time gives the minimal count). We’ll use math to calculate coin counts directly instead of looping through each subtraction.
def calculate_change(amount, denominations): change = {} remaining = amount for coin in denominations: if remaining <= 0: break # Calculate how many of this coin we can use count = remaining // coin if count > 0: change[coin] = count # Update remaining amount using modulus remaining = remaining % coin return change # Define your sorted coin values (descending order is key for greedy) coin_values = [50, 20, 10, 5, 1] try: amount = int(input("How much change do you need? ")) if amount < 0: print("Please enter a non-negative amount.") else: change_result = calculate_change(amount, coin_values) print("##########") for coin, count in change_result.items(): print(f"Number of {coin}p coins = {count}") print("##########") print("End") except ValueError: print("Please enter a valid integer for the amount.")
Why this is better:
- Scalability: No hardcoded coin variables—just update the
coin_valueslist if you need to add/remove denominations. - Efficiency: Uses integer division (
//) and modulus (%) to calculate counts in one step per denomination. Time complexity is O(n) (n = number of coin types), which is way faster than your original O(amount) approach for large sums. - Readability: A modular function separates calculation from input/output, making it easier to teach concepts like function design and code organization.
- Robustness: Includes input validation for non-integers and negative amounts, modeling good error-handling practices.
Teaching extensions for your students:
- Greedy algorithm limitations: Explain that this only works for canonical coin systems. For example, if denominations were [25, 10, 1] and the amount was 30, greedy would pick 25+1+1+1+1 (5 coins), while the optimal is 10+10+10 (3 coins). This is a great lead-in to dynamic programming for non-canonical sets.
- Pluralization: Modify the output to handle plural nouns (e.g., "1 coin" vs "2 coins") for better user experience.
- Alternative algorithms: Challenge students to implement a dynamic programming solution to compare with the greedy approach, highlighting tradeoffs between efficiency and universality.
内容的提问来源于stack exchange,提问作者JC80
相关产品推荐
相关产品推荐

