class Goods:
def __init__(self, goods_list):
self.goods_list = goods_list # List of tuples (name, quantity)
def transfer_goods(self, other_goods, good_index):
"""
Transfer a random amount of goods from self to other_goods.
"""
# Get the name and quantity of the goods to transfer
good_name, self_quantity = self.goods_list[good_index]
if self_quantity > 0:
# Randomly select the amount to transfer
amount = random.randint(1, self_quantity)
print(
f"Transferring {amount} {good_name} from Agent {self.unique_id} to Agent {other_goods.unique_id}")
# Update quantities for the transferred goods
self_goods_amount = self_quantity - amount
other_goods_amount = other_goods.goods_list[good_index][1] + amount
# Update the goods lists
self.goods_list[good_index] = (good_name, self_goods_amount)
other_goods.goods_list[good_index] = (good_name, other_goods_amount)
print(f"After transfer:")
print(f"Agent {self.unique_id}: {self.goods_list}")
print(f"Agent {other_goods.unique_id}: {other_goods.goods_list}")
else:
print(f"Agent {self.unique_id} has no {good_name} to transfer.")
I am currently working on an ABM where the agents are supposed to exchange goods that are in list format ("name", quantity) but I cannot make the list update. All that happens is that the entry of the list is exchange with the entry of the other agent.
I would like the quantity updated if the type is the same and if not have the new entry added.
This all seems to be happening in the transfer_goods() method.
I found a solution to your problem.
I just had to modify a bit the types you used : I added an attribute
unique_idto the classGoods. The rest remains unchanged. The function transfer_goods() transfers the goods from the first to the second list of goods.You just need to make the following assumption : "All Goods have the same
good_namesin theirgoods-list, sorted in the same order". Otherwise it may be better to use dictionaries instead of tuple lists.For example, you can test it with the following goods :