How do you solve this exercise without using a loop?

-1

We want to make a row of bricks that have long goal inches. We have a number of small bricks (1 inch each) and large bricks (5 inches each). Go back True if it is possible to make the goal by choosing between the given bricks.

Function:

def make_bricks(small, big, goal):
.
.
.

Examples:

make_bricks(3, 1, 8)True

make_bricks(3, 1, 9)False

make_bricks(3, 2, 10)True

    
asked by José Ignacio 13.11.2018 в 02:47
source

1 answer

1

Even though I think you have not counted the full statement of the problem, a solution without using loops would be using combinations :

from itertools import combinations

def make_bricks(small, big, goal):
    bricks = [1]*small+[5]*big
    return any(sum(lst)==goal 
               for n in range(len(bricks)+1)
               for lst in combinations(bricks,n) )

It is a brute force algorithm, very inefficient. But it is a solution for simple cases.

Edited

Let's solve it without loops or recursion:

With enough small bricks the solution would be trivial:

goal <= small

Let's calculate how many large bricks we are going to use:

nbig = min(big, goal // 5)

What we have left to reach the goal has to be made with small bricks:

(goal - nbig*5) <= small

Finally:

def make_bricks(small, big, goal):

    nbig = min(big, goal // 5)

    return (goal - nbig*5) <= small

An example using only small bricks to check this solution:

make_bricks(30, 0, 10) --> True
    
answered by 13.11.2018 в 03:54