Skip to content

Instantly share code, notes, and snippets.

@regmicmahesh
Created July 12, 2024 17:23
Show Gist options
  • Save regmicmahesh/0924542561cd4019003ea1e8d55fa229 to your computer and use it in GitHub Desktop.
Save regmicmahesh/0924542561cd4019003ea1e8d55fa229 to your computer and use it in GitHub Desktop.
from fastapi import FastAPI
from dataclasses import dataclass
from pydantic import BaseModel
class Txn(BaseModel):
amount: int
receiver: str
sender: str
class TxnDto(BaseModel):
txns: list[Txn]
api = FastAPI()
@api.post("/")
def add_txns(body: TxnDto):
return calculate(body.txns)
def calculate(txns: list[Txn]) -> list[Txn]:
worth = {}
for txn in txns:
worth[txn.receiver] = 0
worth[txn.sender] = 0
for txn in txns:
receiver = txn.receiver
sender = txn.sender
worth[receiver] += txn.amount
worth[sender] -= txn.amount
receivers = []
senders = []
for k, v in worth.items():
if v < 0:
receivers.append({"name": k, "amount": -v})
else:
senders.append({"name": k, "amount": v})
receivers = sorted(receivers, key=lambda x: x['amount'], reverse=True)
senders = sorted(senders, key=lambda x: x['amount'], reverse=True)
print(receivers, senders)
optimized_txns : list[Txn] = []
while True:
if len(senders) == 0:
break
if len(receivers) == 0:
break
chosen_sender = senders[0]
chosen_receiver = receivers[0]
if chosen_receiver['amount'] < chosen_sender['amount']:
optimized_txns.append(Txn(amount=chosen_receiver['amount'], receiver=chosen_receiver['name'], sender=chosen_sender['name']))
chosen_sender['amount'] -= chosen_receiver['amount']
chosen_receiver['amount'] = 0
if chosen_receiver['amount'] > chosen_sender['amount']:
optimized_txns.append(Txn(amount=chosen_sender['amount'], receiver=chosen_receiver['name'], sender=chosen_sender['name']))
chosen_receiver['amount'] -= chosen_sender['amount']
chosen_sender['amount'] = 0
if chosen_receiver['amount'] == chosen_sender['amount']:
optimized_txns.append(Txn(amount=chosen_sender['amount'], receiver=chosen_receiver['name'], sender=chosen_sender['name']))
del senders[0]
del receivers[0]
continue
if chosen_receiver['amount'] == 0:
del receivers[0]
if chosen_sender['amount'] == 0:
del senders[0]
return optimized_txns
@regmicmahesh
Copy link
Author

@Neeraj319 where is frontend

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment