问题描述
小R有nn部电脑,每部电脑的电池容量分别为aiai。她可以使用两种不同的充电方式来给电脑充电:
- 普通充电:每单位时间为电脑充电xx单位的电量。
- 闪充:每单位时间为电脑充电4x4x单位的电量。
现在,所有电脑的电量都为零。小R希望使用闪充给所有电脑充满电,计算她需要的总充电时间。请保留结果的小数点后两位。
测试样例
样例1:
输入:
n = 4 ,x = 1 ,a = [2, 3, 4, 5]
输出:'3.50'
样例2:
输入:
n = 3 ,x = 2 ,a = [4, 6, 8]
输出:'2.25'
样例3:
输入:
n = 2 ,x = 1 ,a = [10, 5]
输出:'3.75'
def solution(n: int, x: int, a: list) -> str:
total_time = 0.0 # 初始化总充电时间
# 遍历每部电脑的电池容量
for battery_capacity in a:
# 计算使用闪充充满电的时间
time_needed = battery_capacity / (4 * x)
total_time += time_needed # 累加到总充电时间
# 返回格式化后的时间,保留两位小数
return f"{total_time:.2f}"
if __name__ == '__main__':
print(solution(4, 1, [2, 3, 4, 5]) == '3.50') # 输出: True
print(solution(3, 2, [4, 6, 8]) == '2.25') # 输出: True
print(solution(2, 1, [10, 5]) == '3.75') # 输出: True