如何编写符合阶梯式分数规则的列表项数得分计算程序?
解决方案
先明确计分规则:
- 前20项:每项计1分
- 20项之后,每10项为一组,每组单项目得分是前一组的1/2(即第21-30项每项0.5分,31-40项每项0.25分,以此类推)
你不需要复杂的嵌套if语句,用分段计算+循环的方式就能简洁实现需求,完整代码如下:
software_uses = ["Checking email", "Mapping directions", "Checking the weather", "Academic Uses", "Purchasing Goods", "Ask for Help", "Social Media", "Work", "Transportation", "Banking"] total_items = len(software_uses) total_score = 0 # 处理前20项 first_batch = min(total_items, 20) total_score += first_batch * 1 remaining_items = total_items - first_batch # 处理后续每10项的批次 current_score_per_item = 0.5 while remaining_items > 0: batch_size = min(remaining_items, 10) total_score += batch_size * current_score_per_item remaining_items -= batch_size current_score_per_item /= 2 # 按要求向下取整总分 total_score = int(total_score) print(f"Total Items: {total_items}, Total Score: {total_score}")
代码逻辑说明:
- 前20项处理:用
min(total_items,20)兼容列表长度不足20的情况,直接计算这部分得分后,算出剩余待处理的项数。 - 后续批次循环:初始化当前单项目得分为0.5,每次循环取剩余项数和10的较小值作为当前批次的数量,累加对应得分后,剩余项数减少,同时单项目得分减半,直到剩余项数为0。
- 总分取整:用
int()对总分执行向下取整操作,完全符合题目要求。
内容的提问来源于stack exchange,提问作者Axel Palomino
相关产品推荐
相关产品推荐

