【每日一题1026】装满空间

:mage:t2:给定一个顺序排列的列表sizes和数字n,分别代表顺序存储的文件大小和磁盘容量,请编写一个函数,求出该磁盘最多可以顺序存储几个文件。

示例:
输入:([4, 4, 4, 3, 3], 12), 输出:3。因为4+4+4<=12可以存下,而4+4+4+3 > 12存不下。

题目难度:简单
题目来源:codewars: Fill the Hard Disk Drive

def save(sizes: list, n: int) -> int:
    pass

assert save([4,4,4,3,3], 12) == 3
assert save([4,8,15,16,23,42], 108) == 6
assert save([11,13,15,17,19], 8) == 0
def save(sizes: list, n: int) -> int:
    storage = 0
    s_num = 0
    for num in sizes:
        storage += num
        s_num += 1
        if storage >= n:
            break
    return s_num if s_num > 1 else 0


assert save([4, 4, 4, 3, 3], 12) == 3
assert save([4, 8, 15, 16, 23, 42], 108) == 6
assert save([11, 13, 15, 17, 19], 8) == 0
def save(sizes: list, n: int) -> int:
    sum = 0
    for i in range(0,len(sizes)):
        sum = sum + sizes[i]
        if sum > n:
            return i
    return len(sizes)

assert save([4,4,4,3,3], 12) == 3
assert save([4,8,15,16,23,42], 108) == 6
assert save([11,13,15,17,19], 8) == 0
def save(sizes: list, n: int) -> int:
    amount = 0
    i = 0
    for size in sizes:
        amount += size
        i = i + 1
        if amount > n:
            return i - 1
    return i

Python常规思路

def save(sizes: list, n: int) -> int:
    result = []
    for i in range(1, len(sizes)+1):
        sub = sizes[:i]
        if sum(sub) <= n:
            result.append(i)
    return len(result)


assert save([4,4,4,3,3], 12) == 3
assert save([4,8,15,16,23,42], 108) == 6
assert save([11,13,15,17,19], 8) == 0

思路:遍历列表,通过切片循环判断所遍历到的元素及之前元素的总和,再通过判断。如果小于等于则收集。最后返回满足条件的元素的列表长度即可。

1 Like

python参考题解

def save(sizes: list, n: int) -> int:
    data = [item for i, item in enumerate(sizes, 1) if sum(sizes[:i])<=n]
    return len(data)

assert save([4,4,4,3,3], 12) == 3
assert save([4,8,15,16,23,42], 108) == 6
assert save([11,13,15,17,19], 8) == 0

参考思路:通过enumerate函数进行遍历,起始值从1开始,通过条件过滤出合适的元素,然后利用列表推导式收集成列表。最后返回列表长度。

1 Like
def save(sizes: list, n: int) -> int:
    if sizes[0] > n :
        return 0
    elif sum(sizes) <= n:
        return len(sizes)
    else:
        for i in range(len(sizes)):
            if sum(sizes[:i]) >=n:
                return i

assert save([4,4,4,3,3], 12) == 3
assert save([4,8,15,16,23,42], 108) == 6
assert save([11,13,15,17,19], 8) == 0
def save(sizes: list, n: int) -> int:
    s = 0
    k = 0
    for i in sizes:
        s += i
        if s <= n:
            k += 1
        else:
            break
    return k


assert save([4, 4, 4, 3, 3], 12) == 3
assert save([4, 8, 15, 16, 23, 42], 108) == 6
assert save([11, 13, 15, 17, 19], 8) == 0
关闭