[Python] Is there a way to make this code for the lunchbox problem more efficient and more...

Discussão em 'Python' iniciado por Stack, Março 29, 2025.

  1. Stack

    Stack Membro Participativo

    I'm trying to solve a problem where there are n number of lunch boxes and m number of schools. And I'm trying to figure out the maximum amount of school that i could give lunch boxes to.

    • the first line of input is the number of lunchboxes and schools there are
    • and the next input is the number of lunch boxes that a school is required (I either could give no lunch boxes or either give them the exact amount they ask)

    Example input:

    10 4
    3
    9
    4
    2


    Example output:

    3


    This is the code that I'm using

    #import Library
    from itertools import combinations

    #Variables
    Lunchbox_List = []
    Result_List = []

    #Insert number of Lunchbox and School
    Lunchbox, Schools = map(int, input().split())
    #Insert the number of Lunchbox that each school request
    for i in range (1, Schools+1):
    Lunchbox_List.append(int(input()))
    #Count the maximum number of schools
    for j in range (1, len(Lunchbox_List)+1):
    for k in combinations(Lunchbox_List, j):
    if sum(k) <= Lunchbox:
    Result_List.append(k)
    print(len(max(Result_List, key=len)))


    It works but it's slow and kinda hard to read. Is there a way to fix it? I'm new to python.

    Continue reading...

Compartilhe esta Página