如何修改DegreeDays函数,使其输出elif与if分支求和的二元数组
Fixing the DegreeDays Function to Return Sum Totals in the Right Order
Let's sort this out — your current function is collecting individual difference values, but what you need is to calculate the total sum for each condition, then return those sums in the order of the elif branch first, then the if branch.
Here's how to adjust the code:
def DegreeDays(val1): # Initialize sums for each condition heating_total = 0 # For 52 < val < 61: sum of (60 - val) cooling_total = 0 # For 79 < val < 97: sum of (96 - val) for val in val1: if 79 < val < 97: cooling_total += 96 - val elif 52 < val < 61: heating_total += 60 - val # Return totals in the requested order: heating first, then cooling return [heating_total, cooling_total]
Let's test this with your input:
When you call DegreeDays([67, 78, 96, 80, 75, 62, 53]):
- Only
53falls into theelifrange:60 - 53 = 7→heating_totalis 7 96and80fall into theifrange:(96-96) + (96-80) = 0 +16 =16→cooling_totalis16- The function returns
[7, 16], which matches exactly what you need.
The key changes here are:
- Replacing the
resultslist with two sum variables to accumulate totals instead of individual values - Calculating the sum for each condition as we iterate through the input list
- Returning the sums in the specific order you requested (elif branch total first, then if branch total)
内容的提问来源于stack exchange,提问作者user9643452
相关产品推荐
相关产品推荐

