We have answer of your question!

100% solved queries, no empty question

Question: Fetching data from the list


0

Advertisement


I have a dictionary with location and quantity, like

{'loc1': 1000.0,'loc2': 500.0, 'loc3': 200.0,'loc4': 100.0,'loc5': 50.0, }

Now when i'll make a order the scenario should be like below,

  • for 150 quantity it should take product from loc5 and loc4
  • for 210 quantity it should take product from loc3 and loc5
  • for 1777 quantity it should take product from loc1 and loc2 and loc3 and loc4
  • for 530 quantity it should take product from loc2 and loc5.

I don't know how achieve such kind of condition, can anyone sort it out??

Question author Opencurious | Source

Answer


1


Advertisement


Put the quantities in a list, sorted. Use bisect to find an appropriate quantity. Calculate if the lower quantities can fulfill, and if not pick the next higher quantity. Subtract the selected quantity. If still greater than 0, go back to the bisect step.

EDIT:

import bisect

qtys = [50, 100, 200, 500, 1000]

def sack(amt, qtys=qtys):
  res = set()
  while amt > 0:
    pivot = bisect.bisect(qtys, amt)
    if sum(qtys[:pivot]) >= amt:
      amt -= qtys[pivot - 1]
      res.add(pivot - 1)
    else:
      if sum(qtys[:pivot + 1]) < amt:
        raise ValueError('Not enough items to fill the sack')
      res.add(pivot)
      amt -= qtys[pivot]
  return res

print sack(150)
print sack(210)
print sack(1777)
print sack(530)
Answer author Ignacio-vazquez-abrams

Advertisement


Tickanswer.com is providing the only single recommended solution of the question Fetching data from the list under the categories i.e python , dictionary , . Our team of experts filter the best solution for you.

Related Search Queries:

how to retrieve data from list in java , get value from list c# , how to retrieve data from list in c# ,

You may also add your answer!