<p>我按照上面的建议重构了代码以消除重复代码,在合理的情况下使用<code>else</code>而不是<code>elif</code>,修复了<code>hours == 50</code>的缺陷,并引入了dict<code>h</code>来对小时细分进行逻辑分组:</p>
<pre><code>def weeklypaycheck(hours, rate):
h = {'regular': 0, 'overtime': 0, 'extra': 0}
if hours <= 40:
h['regular'] = hours
else:
h['regular'] = 40
if hours <= 50:
h['overtime'] = hours - 40
else:
h['overtime'] = 10
h['extra'] = hours - 50
pay = h['regular'] * rate +\
h['overtime'] * 1.5 * rate +\
h['extra'] * 2 * rate
print(f"This is your pay: {pay}")
</code></pre>
<p>对于这个问题有一种不同的思考方式,即每个小时的最小小时数或最大小时数是多少。这将产生此实现(请注意,只有小时细分计算更改):</p>
<pre><code>def weeklypaycheck(hours, rate):
h = {
'regular': min(hours, 40),
'overtime': max(min(hours - 40, 10), 0),
'extra': max(hours - 50, 0)
}
pay = h['regular'] * rate +\
h['overtime'] * 1.5 * rate +\
h['extra'] * 2 * rate
print(f"This is your pay: {pay}")
</code></pre>
<p>我会测试这样的边界条件:</p>
<pre><code>for hours in [39, 40, 41, 49, 50, 51]:
weeklypaycheck(hours, 1)
</code></pre>
<p>结果是:</p>
<pre><code>This is your pay: 39.0
This is your pay: 40.0
This is your pay: 41.5
This is your pay: 53.5
This is your pay: 55.0
This is your pay: 57.0
</code></pre>