Write a complex python code
- User
Write a complex python code
- Assistant
Here's a complex Python code that demonstrates various concepts and functionalities:
import random import threading import time class BankAccount: def __init__(self, balance): self.balance = balance self.lock = threading.Lock() def withdraw(self, amount): with self.lock: if self.balance >= amount: time.sleep(random.uniform(0, 0.1)) # Simulating processing time self.balance -= amount print(f"Withdrawn: {amount}, New Balance: {self.balance}") else: print("Insufficient funds") def deposit(self, amount): with self.lock: time.sleep(random.uniform(0, 0.1)) # Simulating processing time self.balance += amount print(f"Deposited: {amount}, New Balance: {self.balance}") def transaction_runner(account, transactions): for transaction in transactions: if transaction >= 0: account.deposit(transaction) else: account.withdraw(abs(transaction)) if __name__ == "__main__": account = BankAccount(1000) # Generating random transactions transactions = [random.randint(-100, 100) for _ in range(10)] # Creating threads for concurrent transactions threads = [] for _ in range(5): thread = threading.Thread(target=transaction_runner, args=(account, transactions)) threads.append(thread) thread.start() # Waiting for all threads to complete for thread in threads: thread.join() print(f"Final Balance: {account.balance}") # Generator function for Fibonacci sequence def fibonacci_generator(): a, b = 0, 1 while True: yield a a, b = b, a + b # Iterator for Fibonacci sequence fib = fibonacci_generator() # Printing the first 10 Fibonacci numbers print("Fibonacci Sequence:") for _ in range(10): print(next(fib)) # Lambda function for sorting a list of tuples data = [(2, 'B'), (1, 'A'), (3, 'C')] sorted_data = sorted(data, key=lambda x: x[1]) print("Sorted Data:", sorted_data) # Decorator function for timing a function def timer(func): def wrapper(*args, **kwargs): start_time = time.time() result = func(*args, **kwargs) end_time = time.time() print(f"Execution Time: {end_time - start_time} seconds") return result return wrapper # Applying the timer decorator to a function @timer def my_function(): time.sleep(1) my_function()This code demonstrates the following concepts:
-
Object-Oriented Programming (OOP): The
BankAccountclass represents a bank account with methods for withdrawing and depositing money. -
Multithreading: Multiple threads are created to perform concurrent transactions on the bank account. The
threadingmodule is used for this purpose.
-
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.