Python Forum
Working with Dictionaries - logic seems backward...
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Working with Dictionaries - logic seems backward...
#4
It's just fine where it is. If you move it inside the else you will need to duplicate it for the if as well. However you need to update the inventory with num_sold, not demand

daily_demands = {
  "pear": [6,4,3,2,1],
  "apple": [5,3,2,1,0],
  "orange": [8,6,5,3,2],
  "lemon": [16,14,11,9,7],
}
 
inventory = {"pear": 21, "apple": 20, "orange": 30, "lemon": 0}
 
for fruit, demands in daily_demands.items():
  for demand in demands:
    if demand > inventory[fruit]:
      num_sold = inventory[fruit]
    else:
      num_sold = demand
    inventory[fruit] -= num_sold # change here
print(inventory)
you can even simplify it
for fruit, demands in daily_demands.items():
  for demand in demands:
    num_sold = min(demand, inventory[fruit]) # change here
    inventory[fruit] -= num_sold
or

for fruit, demands in daily_demands.items():
  for demand in demands:
    inventory[fruit] -= min(demand, inventory[fruit]) # change here
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply


Messages In This Thread
RE: Working with Dictionaries - logic seems backward... - by buran - Mar-12-2025, 07:43 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Backward Calculation QuentinL 0 1,984 Nov-15-2019, 01:58 PM
Last Post: QuentinL

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020