Search code examples
pythonlistcounttuplescounter

one counter that works for all veriables


def my_function(account_1,account_2,initiall_amount,log):
    final_list = [account_1_current_balance,account_2_current_balance]
    return final_list
account_1 = 'abc'
account_2 = 'xyz'
initiall_amount = 1000
log = [('abc','xyz',800), ('abc','xyz',100),('xyz','abc',500)]

in the following function i want to creat an e-cash system where i have the sender,reciver, and initall amount that represent the initill amount in both sender and reciver(assume that both have same amount) and the log show the transaction between reciver and sender. here the log consist of trnsaction which have tuple the first element of tuple will be sender the second will be reciver and the third is amount that have to be send now i want to print the current balance in final list
i can solve this by genrating each counter for reciver and sender but i do not want each counter for each reciver and sender because i may have hundreds of reciver and sender i want only one counter that at the end print current balance in sender and reciver account like in the above example the final list that will contain current balance will be [600,1400] here the 600 shows the current amount of account1 , 1400 is of accoun2 becuae at bigning the amount in account1 was 1000 then he send 800 to acount2 so become 200 then he agin send 100 to acount2 so total become 100 after that he recive 500 from account2 so become 600 the same applies for account2 note : i want this this by one counter only


Solution

  • I am not exactly sure if this is what you want, but by making the account a dictionary it will be easier to add/subtract an amount.

    initial_amount = 1000
    account = dict()
    account['abc'] = initial_amount
    account['xyz'] = initial_amount
    logs = [('abc','xyz',800), ('abc','xyz',100),('xyz','abc',500)]
    
    for log in logs:
        #subtract from sender
        account[log[0]] -= log[2]
    
        #add to receiver
        account[log[1]] += log[2]
    
    
    print(account['abc']) #prints out 600
    print(account['xyz']) #prints out 1400