一列列车的最大载客量为n人,这意味着每节车厢的载客量与最大载客量的比例相等。
创建一个函数,该函数返回第一节车厢的索引,该索引容纳其最大容量的50%或更少。如果不存在这样的运输,返回-1。
find_a_seat(200, [35, 23, 18, 10, 40]) ➞ 2
# There are 5 carriages which each have a maximum capacity of 40 (200 / 5 = 40).
# Index 0's carriage is too full (35 is 87.5% of the maximum).
# Index 1's carriage is too full (23 is 57.5% of the maximum).
# Index 2's carriage is good enough (18 is 45% of the maximum).
# Return 2.
def find_a_seat(n, lst):
a = n // len(lst)
return [[i for i, j in enumerate(lst) if j / a <= 0.5]+[-1]][0][0]
print(find_a_seat(200, [35, 23, 18, 10, 40]))你能解释一下为什么我们要循环i,而不是更远地使用它,并且解的结束->-1 --它到底能做什么?
发布于 2021-10-10 17:15:34
[i for i, j in enumerate(lst) if j / a <= 0.5]返回容量为50%的车厢列表,如果有,则返回。这意味着,如果没有,这将是一个空的列表。
[i for i in X if condition]充当过滤器:对于X中的每个元素,如果它们与条件匹配,则保留它们。这里,enumerate(lst)给出了循环的每个步骤的索引(i)和值(j)。
然后,+[-1]在列表的末尾添加-1。如果前面的列表为空,则If将是第一项。
最后,[0][0]分割第一个项目,要么是容量为50%的第一个载货编号,要么是-1。
示范和提供的例子:
>>> [i for i, j in enumerate(lst) if j / a <= 0.5]
[2, 3]
>>> [[i for i, j in enumerate(lst) if j / a <= 0.5]+[-1]]
[[2, 3, -1]]
>>> [[i for i, j in enumerate(lst) if j / a <= 0.5]+[-1]][0]
[2, 3, -1]
>>> [[i for i, j in enumerate(lst) if j / a <= 0.5]+[-1]][0][0]
2可能的备选方案
此解决方案在第一次匹配时停止(如果有的话),否则返回-1。
from itertools import dropwhile
a = n // len(lst)
n = 200
lst = [35, 23, 18, 10, 40]
next(dropwhile(lambda i: lst[i]/a>0.5, range(len(lst))), -1)https://stackoverflow.com/questions/69517261
复制相似问题