Settling Balance in Python

Viewed 68

Just wanted to know let's say Person 1: Paid 66USD Person 2: Paid 0USD Person 3: Paid 33USD

How do I program it in a way that it sends a table that tells person 2 has to pay 33USD TO person 1 to settle an equal balance amongst all members?

print('How many people in total')
people_num = int(input())

#Get the name list of everyone
name_list = []
for num in range(0,people_num):
    print("What are their names?")
    name_list.append(input())
print(name_list)

#get the amount everyone paid
amount = []
for name in name_list:
    print("How much did " + name + " pay?")
    amount.append(float(input()))

total_amount = sum(amount)
print(total_amount)

#create empty dictionary to calculate how much one person has to pay or receive 
owe = []
for x in amount:
    owe.append(round(x - (total_amount/people_num),2))

info = {}
for name, amt_owe in zip(name_list,owe):
    info[name] = amt_owe
print(info)```
3 Answers

Here is a solution

def find_transactions(info):
    for i in info.keys():
        # find a negative balance : user A
        if info[i] < 0:
            for j in info.keys():

                # find a positive balance : user B
                if info[j] > 0 and i != j:

                    # user A will pay user B
                    x = abs(info[i])
                    if x > info[j]:
                        x = abs(info[j])

                    # change values of balances of user A and B
                    info[j] = info[j]-x
                    info[i] = info[i]+x

                    print(f"{i} pay {x} to {j}")
    return info

Let's try with different values

people_num = 3
name_list = ["a", "b", "c"]
amount = [66, 0, 33]

in : info = {'a': 33.0, 'b': -33.0, 'c': 0.0}

out : 
b pay 33.0 to a
info = {'a': 0.0, 'b': 0.0, 'c': 0.0}

amount = [66, 33, 33]

in : info = {'a': 22.0, 'b': -11.0, 'c': -11.0}

out : 
b pay 11.0 to a
c pay 11.0 to a
info = {'a': 0.0, 'b': 0.0, 'c': 0.0}

The simple solution to this would be to count person's balance iterating through a list.

def process_transaction(from_user, to_user, amount):
  if from_user['balance'] >= amount:
    to_user['balance'] += amount
    from_user['balance'] -= amount
    print("Transaction success")
  else:
    print("Transaction failed")

bob = {"balance":100}
alice = {"balance":50}
process_transaction(bob, alice, 50)
print(bob)
print(alice)

does this help you ?

def info():
    return {_name: _amount for _name, _amount in zip(name_list, amount)}


def equal_balances(_info):
    # Make the transaction between sender and receiver
    def transaction(payment_amount):
        # print(f"balance before payment: {sender}: {round(_info[sender])}, {receiver}: {round(_info[receiver])}")
        _info[receiver] += payment_amount
        _info[sender] -= payment_amount
        print(f"{sender} pay {round(payment_amount, 2)} to {receiver}")
        # print(f"balance after payment: {sender}: {round(_info[sender])}, {receiver}: {round(_info[receiver])}")

    medium_amount = total_amount / people_num  # get medium amount
    # get hwo pay hwo
    print(f'The medium amount is: {round(medium_amount, 2)}')
    for sender in _info:
        if _info[sender] > medium_amount:
            for receiver in _info:
                if _info[sender] > medium_amount > _info[receiver]:
                    receiver_need = medium_amount - _info[receiver]
                    if _info[sender] - receiver_need < medium_amount:
                        transaction(_info[sender] - medium_amount)
                    elif _info[sender] >= receiver_need:
                        transaction(receiver_need)
                    elif _info[sender] - receiver_need == medium_amount:
                        transaction(_info[sender] - medium_amount)

    return _info


people_num = int(input('How many people in total? '))

# Get the name list of everyone
name_list = []
for num in range(0, people_num):
    name_list.append(input('What are their names? '))
print(name_list)

# get the amount everyone paid
amount = []
for name in name_list:
    amount.append(float(input(f'How much did {name} pay? ')))

total_amount = sum(amount)
print(total_amount)

people_info = info()
print(people_info)
people_info = equal_balances(people_info)
print(people_info)
Related