简体   繁体   中英

While loop program multiple prints and skips conditions?

Creating a program where I can determine whether I can fit a desired kg of material exactly in a set of 5kg and 1kg containers. The problem is that for some reason the functions always print -1 when it is supposed to do it only if all the conditions fail. Also, for some numbers, it randomly stops working.

The program has 3 inputs:

  • the amount of 5kg boxes,
  • 1kg boxes and
  • the amount of kg material in need of packaging.

It needs to calculate how many boxes are needed if it is even possible. It must use all of the 5kg boxes first if possible. If it can't be done with exact amounts, it needs to print -1.


For example.

  1. I have
  • 2x 5kg boxes,

  • 6x 1kg boxes

  • 14kg of material.

    At first, I need to use all of the 5kg boxes. Now I have 10kg packed into 2 5kg boxes and 4kg of material left. I have 6 1kg boxes, so I take 4 boxes from there and are left with in total of 6 boxes used in order to package it.

  1. If I have
  • 2x 5kg boxes,
  • 2x 1kg boxes
  • 15kg of material,

the program should print out -1, since it isn't possible to pack it.

Here is what I have tried so far:

s = int(input("Amount of 5kg boxes: "))
v = int(input("Amount of 1kg boxes: "))
k = int(input("Material in kg's: "))

def box(a, b, c):
    kar = 0
    while c>=5 and a>0:
        c = c-5
        a = a-1
        kar = kar + 1
        if c == 0:
            print(kar)
        else:
            if b>=c:
                kar = kar + c
                print(kar)
            else:
                print(-1)
        
        
box(s, v, k)

You only need some math

def box(box_5, box_1, amount):
    return (amount - min(box_5, amount // 5) * 5) <= box_1

# same but splitted to get it
def box(box_5, box_1, amount):
    nb_box5_that_can_be_used = min(box_5, amount // 5)
    amount -= nb_box5_that_can_be_used * 5
    return amount <= box_1

A loop version, so you can get it differently

def box(box_5, box_1, amount):
    while amount >= 5 and box_5 > 0:
        amount -= 5
        box_5 -= 1
    return amount <= box_1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM