# Python Program to find out the size of the bus that can contain all the friends in the group

PythonServer Side ProgrammingProgramming

Suppose, there are n number of student groups waiting to get back from their college to their home via the college bus. In each student group, there are m number of students. The student groups want to travel by bus without getting separated. They board the bus if and only if all the members of their group can get on the bus. Also, a group does not board the bus if their previous group has not boarded the bus or has already reached their destination. If we are given the number of groups and the number of students in each group, we have to find out the size of the bus so the bus can transport all the groups, and every time the bus starts from the college there is no empty space in the bus.

So, if the input is like groups or gr_no = [3, 4, 2, 2, 1, 4, 3, 5], then the output will be [12, 24].

If the bus size is 12, it can contain groups 1 - 5 on the first trip, and the rest of the groups on the second trip.

If the bus size is 24, it can contain all groups and transport them on one trip only.

To solve this, we will follow these steps −

• Define a function factor_ret() . This will take n
• for i in range (0 to n ^ 0.5), do
• if n mod i is same as 0, then
• add a tuple(i, floor value of (n/i)) into output_list
• sort the list output_list
• return output_list as a set
• Now perform the following steps −
• total := a new list containing item gr_no[0]
• for i in range 1 to size of gr_no, do
• insert total[i - 1] + gr_no[i] at the end of total
• b_sizes := a new list
• for each size in factor_ret(sum of list (gr_no)), do
• temp_list := a new list from all non-zero elements from total
• index := 1
• indicator := True
• for each point in temp_list, do
• if point is not same as size * index, then
• indicator := False
• come out from the loop
• index := index + 1
• if indicator is True, then
• insert size at the end of b_sizes
• return b_sizes

## Example

Let us see the following implementation to get better understanding −

Live Demo

from functools import reduce
def solve(gr_no):
total = [gr_no[0]]
for i in range(1, len(gr_no)):
total.append(total[i - 1] + gr_no[i])
b_sizes = []
for size in factor_ret(sum(gr_no)):
temp_list = list(filter(lambda x : x % size == 0, total))
index = 1
indicator = True
for point in temp_list:
if point != size * index:
indicator = False
break
index += 1
if indicator:
b_sizes.append(size)
return b_sizes
def factor_ret(n):
return sorted(set(reduce(list.__add__, ([i, n//i] for i in range(1, int(n**0.5) + 1) if n % i == 0))))
print(solve([3, 4, 2, 2, 1, 4, 3, 5]))

## Input

[3, 4, 2, 2, 1, 4, 3, 5]

## Output

[12, 24]
Updated on 18-May-2021 05:47:07