shabieh2 - 6 months ago 24

Python Question

How do you solve this problem using python?

You load luggage into container. Once container reaches its limit (100 lbs). You move onto the next container. This is how you load the luggage.

When it is time to unload the data, you will first unload the last loaded container (which is less than 100lbs. And from it , you will remove the first loaded luggage, then second, etc.) Then you will move to the next container.

If the question is not clear.

Here is what the loading array looks like

Say we have 3 containers and here was the loading arrangement

[30,45,15,25,50,20,30,60]

The last item in this array is the first loaded. After the second luggage, the first container could not accommodate a 20lb luggage, so that went into the next container.

20,50,25 went into the second, and 15,45,30 went into the last one.

When it is time to unload, we start with the first luggage of the last container, and move in that order.

Therefore the unloading array is

[15,45,30,20,50,25,60,30]

Is there a function that can convert the input into the output?

Keeping in mind, that each container must be kept under 100 lbs??

Any thoughts or ideas?

Sorry if the question rambles, this is my first question on stack

THANKS!

Here is what I have tried thus far:

A=[15,20,25,45,20,30,65]

output=[20,15,20,45,25,65,30]

`def input_output(A):`

for i in range(1,len(A)):

B=[]*len(A)

if A[-i]<100:

B[0]=A[-i]

B[i]=A[-i-1]+B[i-1]

if B[i]>100:

for j in range(1,i):

C=[]*len(A)

C[-i]=A[i-len(A)]# Need a subarray to get reversed.

#I don't feel this is going the right direction

# C is my intended output array

Answer

You need to think about your algorithm.

You are creating bins based on 100, so construct them and then deconstruct to get your expected output. Using `[-1]`

as the index means always add to the last bin in `bins`

:

```
A = [15,20,25,45,20,30,65]
bins = [[]]
for i in reversed(A):
if sum(bins[-1]) + i > 100:
bins.append([])
bins[-1].append(i)
>>> bins
[[65, 30], [20, 45, 25], [20, 15]]
```

So you just need to reverse and flatten the bins and this can be done a number of ways:

```
>>> [a for b in reversed(bins) for a in b]
[20, 15, 20, 45, 25, 65, 30]
# Or
>>> sum(reversed(bins), [])
[20, 15, 20, 45, 25, 65, 30]
# Or
>>> import itertools as it
>>> list(it.chain.from_iterable(reversed(bins)))
[20, 15, 20, 45, 25, 65, 30]
```