Check if item can be measured using a scale and some weights in Python


Suppose we have some weights like a^0, a^1, a^2, …, a^100, here 'a' is an integer, and we also have a weighing scale where weights can be put on both the sides of that scale. We have to check whether a particular item of weight W can be measured using these weights or not.

So, if the input is like a = 4, W = 17, then the output will be True the weights are a^0 = 1, a^1 = 4, a^2 = 16, we can get 16 + 1 = 17.

To solve this, we will follow these steps −

  • found := False
  • Define a function util() . This will take idx, itemWt, weights, N
  • if found is true, then
    • return
  • if itemWt is same as 0, then
    • found := True
    • return
  • if idx > N, then
    • return
  • util(idx + 1, itemWt, weights, N)
  • util(idx + 1, itemWt + weights[idx], weights, N)
  • util(idx + 1, itemWt - weights[idx], weights, N)
  • From the main method do the following −
  • if a is either 2 or 3, then
    • return True
  • weights := a list of size 100 and fill with 0
  • total_weights := 0
  • weights[0] := 1, i := 1
  • Do the following infinitely, do
    • weights[i] := weights[i - 1] * a
    • total_weights := total_weights + 1
    • if weights[i] > 10^7
      • come out from loop
    • i := i + 1
  • util(0, W, weights, total_weights)
  • if found true, then
    • return True
  • return False

Example

Let us see the following implementation to get better understanding −

 Live Demo

found = False
def util(idx, itemWt, weights, N):
   global found
   if found:
      return
   if itemWt == 0:
      found = True
      return
   if idx > N:
      return
   util(idx + 1, itemWt, weights, N)
   util(idx + 1, itemWt + weights[idx], weights, N)
   util(idx + 1, itemWt - weights[idx], weights, N)
def solve(a, W):
   global found
   if a == 2 or a == 3:
      return True
   weights = [0] * 100
   total_weights = 0
   weights[0] = 1
   i = 1
   while True:
      weights[i] = weights[i - 1] * a
      total_weights += 1
      if weights[i] > 10**7:
         break
      i += 1
   util(0, W, weights, total_weights)
   if found:
      return True
   return False
a = 4
W = 17
print(solve(a, W))

Input

4, 17

Output

True

Updated on: 19-Jan-2021

189 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements