Implement the BankAccount class. The entire project merely consists of inheriting from this class and adding new functionality, specifically:
Create a subclass of BankAccount called SavingsAccount that has, in addition to the balance and history, an allotment of money in various categories. The allotment is an associative array involving (category, value) pairs. For instance, a sample allotment is: {('education',20),('marriage',30),('parking tickets',70),('Having Naren for teaching CS000', priceless)}. The idea of allotment is to describe how the "balance" (from BankAccount) is distributed. So, if the balance is 1000, and allotment is: {('education',10),('marriage',30)} then the bar chart will show two bars: one of height 750 for marriage.
Assistant
User
Okay, I want you to use a different library other than matplotlib. Also I need additional functionalities like offering user to enter their own input and with options like deposit, withdraw, get balance and transaction history, new savings account creation, create savings plan and showing graphs
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
(Extra Credit: 15%) Implement a message in SavingsAccount that presents the percentage distribution of allotments in the form of a pie chart, with each slice of a different color and clearly labeled with the corresponding category.
I'll guide you through implementing this BankAccount class and its subclass SavingsAccount in Python. The BankAccount class will be fairly simple, just tracking a balance and a history of transactions. The SavingsAccount class will add functionality for managing allotments as described, including methods to initialize, plan savings, show the distribution of savings in different categories through a bar chart, and for extra credit, present the distribution as a pie chart.
Let's start with the implementation of the base BankAccount class:
Now, let's move to the SavingsAccount class which will extend BankAccount. We will also include the visualization functionality using matplotlib for plotting the distributions as bar and pie charts:
python
import matplotlib.pyplot as plt
class SavingsAccount(BankAccount):
def __init__(self):
super().__init__() # Initialize balance and history from parent class
self.allotment = {} # For storing the (category, value) pairs
def initialize(self):
self.balance = 0
self.history = []
self.allotment = {}
def plan_savings(self, factor: int, reason: str):
self.allotment[reason] = factor
def show_distribution(self):
labels = list(self.allotment.keys())
factors = list(self.allotment.values())
total_factor = sum(factors)
amounts = [(self.balance * factor / total_factor) for factor in factors]
plt.figure(figsize=(10, 5))
plt.bar(labels, amounts, color='skyblue')
plt.xlabel('Categories')
plt.ylabel('Amount ($)')
plt.title('Distribution of Savings')
plt.show()
def show_percentage_distribution(self):
labels = list(self.allotment.keys())
factors = list(self.allotment.values())
total_factor = sum(factors)
sizes = [(factor / total_factor) * 100 for factor in factors]
fig1, ax1 = plt.subplots()
ax1.pie(sizes, labels=labels, autopct='%1.1f%%', startangle=90)
ax1.axis('equal') # Equal aspect ratio ensures that pie is drawn as a circle.
plt.title('Percentage Distribution of Savings')
plt.show()
To use the SavingsAccount class, make sure you have matplotlib installed in your Python environment. You can install it using pip:
code
pip install matplotlib
Here is a quick example demonstrating how to create a SavingsAccount instance, plan for some savings, and visualize the distribution:
python
# Create a new savings account
account = SavingsAccount()
# Add some balance
account.deposit(1000)
# Plan savings
account.plan_savings(10, 'education')
account.plan_savings(30, 'marriage')
# Show the distribution of funds towards different goals
account.show_distribution()
# For extra credit: Show the percentage distribution
account.show_percentage_distribution()
Remember, the visualization will work if you're using this code in an environment that supports displaying graphical output, such as Jupyter notebooks or directly within a Python interactive shell that has GUI support.
For a different visualization library, we can use plotly, a popular library for creating interactive charts. It provides a more dynamic experience compared to matplotlib. You'll need to install it by running pip install plotly.
About adding functionality for user input and interaction, I'll create a simple text-based UI in Python that allows users to interact with their bank and savings accounts. Through this interface, users can deposit, withdraw, check the balance and transaction history, create new savings accounts, plan savings, and view distributions as interactive graphs.
Let's upgrade both the BankAccount and SavingsAccount class to include these functionalities:
BankAccount Class
This class remains the same as before, as we're focusing on expanding the SavingsAccount.
SavingsAccount Class with UI and plotly
python
import plotly.graph_objects as go
from plotly.subplots import make_subplots
class BankAccount:
def __init__(self):
self.balance = 0
self.history = []
def deposit(self, amount):
self.balance += amount
self.history.append(('Deposit', amount))
def withdraw(self, amount):
if amount > self.balance:
print("Insufficient funds")
return False
self.balance -= amount
self.history.append(('Withdrawal', amount))
return True
def get_balance(self):
return self.balance
def get_history(self):
return self.history
class SavingsAccount(BankAccount):
def __init__(self):
super().__init__()
self.allotment = {}
def plan_savings(self, factor: int, reason: str):
self.allotment[reason] = factor
def show_distribution(self):
labels = list(self.allotment.keys())
factors = list(self.allotment.values())
total_factor = sum(factors)
amounts = [(self.balance * factor / total_factor) for factor in factors]
fig = go.Figure(data=[go.Bar(x=labels, y=amounts)])
fig.update_layout(title='Distribution of Savings',
xaxis_title='Categories',
yaxis_title='Amount ($)')
fig.show()
def show_percentage_distribution(self):
labels = list(self.allotment.keys())
factors = list(self.allotment.values())
total_factor = sum(factors)
sizes = [(factor / total_factor) * 100 for factor in factors]
fig = make_subplots(rows=1, cols=1, specs=[[{'type':'domain'}]])
fig.add_trace(go.Pie(labels=labels, values=sizes, name="Savings"))
fig.update_traces(hole=.4, hoverinfo="label+percent+name")
fig.update_layout(title_text="Percentage Distribution of Savings")
fig.show()
def user_interface():
account = None
while True:
if account is None:
print("\n1. Create Savings Account\n0. Exit")
choice = input("Choose an option: ")
if choice == '1':
account = SavingsAccount()
print("Savings Account Created Successfully!")
elif choice == '0':
break
else:
print("\n1. Deposit\n2. Withdraw\n3. Get Balance\n4. Get Transaction History\n5. Create Savings Plan\n6. Show Distribution Graph\n7. Show Percentage Distribution Graph\n8. Create Another Savings Account\n0. Exit")
choice = input("Choose an option: ")
if choice == '1':
amount = float(input("Enter amount to deposit: "))
account.deposit(amount)
print(f"${amount} deposited successfully.")
elif choice == '2':
amount = float(input("Enter amount to withdraw: "))
if account.withdraw(amount):
print(f"${amount} withdrawn successfully.")
elif choice == '3':
print(f"Current Balance: ${account.get_balance()}")
elif choice == '4':
print("Transaction History:")
for transaction in account.get_history():
print(f"{transaction[0]}: ${transaction[1]}")
elif choice == '5':
reason = input("Enter the reason for saving: ")
factor = int(input(f"Enter the saving factor for {reason}: "))
account.plan_savings(factor, reason)
print(f"Savings plan for {reason} created successfully.")
elif choice == '6':
account.show_distribution()
elif choice == '7':
account.show_percentage_distribution()
elif choice == '8':
account = SavingsAccount()
print("New Savings Account Created Successfully!")
elif choice == '0':
break
if __name__ == "__main__":
user_interface()
This code block includes both the BankAccount and SavingsAccount class definitions, additional functionalities, and a simple UI to interact with the classes. The user_interface function drives the UI, allowing users to perform various banking and savings account operations, including creating visualizations.
To interact with the system, run the script and follow the on-screen prompts. Make sure you have plotly installed in your environment to enable the visualization features.