summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authormo khan <mo@mokhan.ca>2025-04-17 07:21:28 -0600
committermo khan <mo@mokhan.ca>2025-04-17 07:21:28 -0600
commitacb1a5354cae6183af6a13c0c762a7ca13ce2103 (patch)
treec5409dc6cab9dfe80dcb09be97f0348af52b9d6b
parent15f39928342d1155cde4098c7b92f58436887ba2 (diff)
refactor: collapse procedural code into a loop
-rw-r--r--coins2.py21
1 files changed, 8 insertions, 13 deletions
diff --git a/coins2.py b/coins2.py
index a0b33b5..9fe2577 100644
--- a/coins2.py
+++ b/coins2.py
@@ -4,7 +4,7 @@ DIME = 0.10
NICKEL = 0.05
PENNY = 0.01
-def coins(total, coin):
+def num_coins(total, coin):
if total < coin:
return 0
@@ -14,20 +14,15 @@ def coins(total, coin):
def reduce(total, coin, number_of_coins):
return round(total - (number_of_coins * coin), 2)
-def calculate(total):
- quarters = coins(total, QUARTER)
- total = reduce(total, QUARTER, quarters)
+def calculate(total, coins = [QUARTER, DIME, NICKEL, PENNY]):
+ result = [0, 0, 0, 0]
- dimes = coins(total, DIME)
- total = reduce(total, DIME, dimes)
+ for i, coin in enumerate(coins):
+ count = num_coins(total, coin)
+ total = reduce(total, coin, count)
+ result[i] = count
- nickels = coins(total, NICKEL)
- total = reduce(total, NICKEL, nickels)
-
- pennies = coins(total, PENNY)
- total = reduce(total, PENNY, pennies)
-
- return [quarters, dimes, nickels, pennies]
+ return result
def receipt(total):
coins = calculate(total)