w3resource

Python: Find the first negative balance


First Negative Balance

Write a Python program to find the first negative balance from a given list of numbers that represent bank deposits and withdrawals.

Input:
[[12, -7, 3, -89, 14, 88, -78], [-1, 2, 7]]

Output:
[-81, -1]
Input:
[[1200, 100, -900], [100, 100, -2400]]

Output:
[None, -2200]

Visual Presentation:

Python: Find the first negative balance .

Sample Solution:

Python Code:

# License: https://bit.ly/3oLErEI

# Define a function named 'test' that takes a list of balances as input
def test(balances):
    firsts = []  # Initialize an empty list to store the first negative balances
    
    # Iterate over each list of balances in the input list
    for bals in balances:
        total = 0  # Initialize a variable to store the running total of balances
        
        # Iterate over each balance in the list of balances
        for b in bals:
            total += b  # Update the running total with the current balance
            
            # Check if the running total becomes negative
            if total < 0:
                firsts.append(total)  # Append the first negative balance to the result list
                break
        else:
            firsts.append(None)  # If no negative balance is found, append None to the result list
    
    return firsts  # Return the list of first negative balances

# Example 1
balances1 = [[12, -7, 3, -89, 14, 88, -78], [-1, 2, 7]]
print("Bank deposits and withdrawals:")
print(balances1)
print("\nFirst negative balance of deposits and withdrawals:")
print(test(balances1))

# Example 2
balances2 = [[1200, 100, -900], [100, 100, -2400]]
print("\nBank deposits and withdrawals:")
print(balances2)
print("\nFirst negative balance of deposits and withdrawals:")
print(test(balances2))

Sample Output:

Bank deposits and withdrawals:
[[12, -7, 3, -89, 14, 88, -78], [-1, 2, 7]]

First negative balance of deposits and withdrawals:
[-81, -1]
Bank deposits and withdrawals:
[[1200, 100, -900], [100, 100, -2400]]

First negative balance of deposits and withdrawals:
[None, -2200]

Flowchart:

Flowchart: Python - Find the first negative balance .

Python Code Editor :

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Create a new string by taking s, and word by word rearranging its characters in ASCII order.
Next: Inject a number in between each pair of adjacent numbers in a list of numbers.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.