From 0833c574c401d1d862c8a8b1ebd2e7fcf6c2f4b2 Mon Sep 17 00:00:00 2001 From: jassi Date: Fri, 2 Aug 2024 19:33:56 +0530 Subject: [PATCH] added in_memory_db practice in various scenarios --- .gitignore | 1 + exercises/in_memory_db.py | 83 ++++++++++++++ exercises/in_memory_db_cmd.py | 109 ++++++++++++++++++ exercises/in_memory_db_json.py | 158 +++++++++++++++++++++++++++ exercises/in_memory_db_persistent.py | 104 ++++++++++++++++++ exercises/requirements.txt | 91 +++++++++++++++ 6 files changed, 546 insertions(+) create mode 100755 exercises/in_memory_db.py create mode 100755 exercises/in_memory_db_cmd.py create mode 100755 exercises/in_memory_db_json.py create mode 100755 exercises/in_memory_db_persistent.py create mode 100644 exercises/requirements.txt diff --git a/.gitignore b/.gitignore index a708c31..ac4474b 100644 --- a/.gitignore +++ b/.gitignore @@ -122,6 +122,7 @@ venv.bak/ # Ignore text *.txt !requirements.txt +*.json # Ignore mp3 *.mp3 diff --git a/exercises/in_memory_db.py b/exercises/in_memory_db.py new file mode 100755 index 0000000..546eb8e --- /dev/null +++ b/exercises/in_memory_db.py @@ -0,0 +1,83 @@ +# The problem requires implementing an in-memory key-value store +# where you can set a key-value pair and +# retrieve the value of a key. + +# Example: +# db.set(101, ["Sanjeev", "ProdSec"]) +# db.set(102, ["Deep", "DevSecOps"]) +# db.get(102) +# Think of command line for n inputs, set for n inputs, then based on command implement get, delete +# Example: +# Choose below options for operations: +# 1. set/create entries +# How many entries: 2 +# emp_id: input +# emp_details: input([]) +# 2. get emp_id details +# 3. delete emp_id details +# 4. update emp_id details + +class DB: + + def __init__(self): + self.dic = {} + + def set(self, key: int, value: list) -> None: + if not isinstance(key, int): + raise TypeError("Key must be an integer") + if not isinstance(value, list): + raise TypeError("Value must be a list") + if key in self.dic: + raise ValueError(f"Key {key} already exists") + self.dic[key] = value + + def get(self, key: int) -> list: + if not isinstance(key, int): + raise TypeError("Key must be an integer") + if key in self.dic: + return self.dic[key] + else: + print(f"No record found for emp id: {key}") + return None + + def delete(self, key: int) -> None: + if not isinstance(key, int): + raise TypeError("Key must be an integer") + if key in self.dic: + print(f"Deleting emp id {key} details: {self.dic[key]}") + del self.dic[key] + print(f"Emp id {key} deleted successfully.") + else: + print(f"No record found for emp id: {key}") + + print(f"Current employee list: {self.dic}") + +# Example usage +db = DB() + +# Add employees +try: + db.set(101, ["Jassi", "ProdSec"]) + db.set(102, ["Deep", "DevSecOps"]) + db.set(103, ["Deepraj Barman", "Developer"]) + db.set(104, ["Himanshu", "AppSec"]) + # Attempting to add an employee with an existing key + db.set(101, ["Alex", "Security"]) +except (TypeError, ValueError) as e: + print(e) + +# Get emp details +try: + details = db.get(102) + if details: + print(f"Emp id 102 details: {details}") +except TypeError as e: + print(e) + +# Delete emp details +try: + db.delete(102) +except TypeError as e: + print(e) + + diff --git a/exercises/in_memory_db_cmd.py b/exercises/in_memory_db_cmd.py new file mode 100755 index 0000000..bfdb120 --- /dev/null +++ b/exercises/in_memory_db_cmd.py @@ -0,0 +1,109 @@ +# The problem requires implementing an in-memory key-value store +# where you can set a key-value pair and +# retrieve the value of a key. + +# Example: +# db.set(101, ["Sanjeev", "ProdSec"]) +# db.set(102, ["Deep", "DevSecOps"]) +# db.get(102) +# Think of command line for n inputs, set for n inputs, then based on command implement get, delete +# Example: +# Choose below options for operations: +# 1. set/create entries +# How many entries: 2 +# emp_id: input +# emp_details: input([]) +# 2. get emp_id details +# 3. delete emp_id details +# 4. update emp_id details + +import argparse + +class DB: + + def __init__(self): + self.dic = {} + + def set(self, key: int, value: list) -> None: + if not isinstance(key, int): + raise TypeError("Key must be an integer") + if not isinstance(value, list): + raise TypeError("Value must be a list") + if key in self.dic: + raise ValueError(f"Key {key} already exists") + self.dic[key] = value + + def get(self, key: int) -> list: + if not isinstance(key, int): + raise TypeError("Key must be an integer") + if key in self.dic: + return self.dic[key] + else: + print(f"No record found for emp id: {key}") + return None + + def delete(self, key: int) -> None: + if not isinstance(key, int): + raise TypeError("Key must be an integer") + if key in self.dic: + print(f"Deleting emp id {key} details: {self.dic[key]}") + del self.dic[key] + print(f"Emp id {key} deleted successfully.") + else: + print(f"No record found for emp id: {key}") + + print(f"Current employee list: {self.dic}") + +def main(): + parser = argparse.ArgumentParser(description="Database operations") + subparsers = parser.add_subparsers(dest="command") + + # Set command + set_parser = subparsers.add_parser('set', help="Set a new entry") + set_parser.add_argument("key", type=int, help="Key (employee ID)") + set_parser.add_argument("value", type=str, nargs='+', help="Value (employee details)") + + # Get command + get_parser = subparsers.add_parser("get", help="Get an entry") + get_parser.add_argument("key", type=int, help="Key (employee ID)") + + # Delete command + delete_parser = subparsers.add_parser("delete", help="Delete an entry") + delete_parser.add_argument("key", type=int, help="Key (employee ID)") + + args = parser.parse_args() + db = DB() + + # Example preloaded entries + try: + db.set(101, ["Jassi", "ProdSec"]) + db.set(102, ["Deep", "DevSecOps"]) + db.set(103, ["Deepraj Barman", "Developer"]) + db.set(104, ["Himanshu", "AppSec"]) + except (TypeError, ValueError) as e: + print(e) + + if args.command == "set": + try: + db.set(args.key, args.value) + print(f"Set key {args.key} with value {args.value}") + except (TypeError, ValueError) as e: + print(e) + + elif args.command == "get": + try: + details = db.get(args.key) + if details: + print(f"Emp id {args.key} details: {details}") + except TypeError as e: + print(e) + + elif args.command == "delete": + try: + db.delete(args.key) + except TypeError as e: + print(e) + +if __name__ == "__main__": + main() + diff --git a/exercises/in_memory_db_json.py b/exercises/in_memory_db_json.py new file mode 100755 index 0000000..c1ed09d --- /dev/null +++ b/exercises/in_memory_db_json.py @@ -0,0 +1,158 @@ +# The problem requires implementing an in-memory key-value store +# where you can set a key-value pair and +# retrieve the value of a key. + +# Example: +# db.set(101, ["Sanjeev", "ProdSec"]) +# db.set(102, ["Deep", "DevSecOps"]) +# db.get(102) +# Think of command line for n inputs, set for n inputs, then based on command implement get, delete +# Example: +# Choose below options for operations: +# 1. set/create entries +# How many entries: 2 +# emp_id: input +# emp_details: input([]) +# 2. get emp_id details +# 3. delete emp_id details +# 4. update emp_id details +# use loop for interactive session +# usr argparse for cmd options +# use json to store the data for permanent use +# handle as much error as you can, also some edge cases +import argparse +import json +import os + +class DB: + def __init__(self, filename='db.json'): + self.filename = filename + self.dic = self.load() + + def load(self): + if os.path.exists(self.filename): + with open(self.filename, 'r') as f: + return json.load(f) + return {} + + def save(self): + with open(self.filename, 'w') as f: + json.dump(self.dic, f, indent=4) + + def set(self, key: int, value: list) -> None: + if not isinstance(key, int): + raise TypeError("Key must be an integer") + if not isinstance(value, list): + raise TypeError("Value must be a list") + if key in self.dic: + raise ValueError(f"Key {key} already exists") + self.dic[key] = value + self.save() + + def get(self, key: int) -> list: + if not isinstance(key, int): + raise TypeError("Key must be an integer") + if key in self.dic: + return self.dic[key] + else: + print(f"No record found for emp id: {key}") + return None + + def delete(self, key: int) -> None: + if not isinstance(key, int): + raise TypeError("Key must be an integer") + if key in self.dic: + print(f"Deleting emp id {key} details: {self.dic[key]}") + del self.dic[key] + print(f"Emp id {key} deleted successfully.") + self.save() + else: + print(f"No record found for emp id: {key}") + print(f"Current employee list: {self.dic}") + +def main(): + db = DB() + + parser = argparse.ArgumentParser(description="Database operations") + subparsers = parser.add_subparsers(dest="command") + + # Set command + set_parser = subparsers.add_parser("set", help="Set a new entry") + set_parser.add_argument("key", type=int, help="Key (employee ID)") + set_parser.add_argument("value", nargs='+', help="Value (employee details)") + + # Get command + get_parser = subparsers.add_parser("get", help="Get an entry") + get_parser.add_argument("key", type=int, help="Key (employee ID)") + + # Delete command + delete_parser = subparsers.add_parser("delete", help="Delete an entry") + delete_parser.add_argument("key", type=int, help="Key (employee ID)") + + args = parser.parse_args() + + if args.command == "set": + try: + db.set(args.key, args.value) + print(f"Set key {args.key} with value {args.value}") + except (TypeError, ValueError) as e: + print(e) + + elif args.command == "get": + try: + details = db.get(args.key) + if details: + print(f"Emp id {args.key} details: {details}") + except TypeError as e: + print(e) + + elif args.command == "delete": + try: + db.delete(args.key) + except TypeError as e: + print(e) + + else: + while True: + print("\nChoose an operation:") + print("1. Set a new entry") + print("2. Get an entry") + print("3. Delete an entry") + print("4. Exit") + + choice = input("Enter your choice (1/2/3/4): ") + + if choice == '1': + try: + key = int(input("Enter key (employee ID): ")) + value = input("Enter value (employee details separated by spaces): ").split() + db.set(key, value) + print(f"Set key {key} with value {value}") + except (TypeError, ValueError) as e: + print(e) + + elif choice == '2': + try: + key = int(input("Enter key (employee ID): ")) + details = db.get(key) + if details: + print(f"Emp id {key} details: {details}") + except TypeError as e: + print(e) + + elif choice == '3': + try: + key = int(input("Enter key (employee ID): ")) + db.delete(key) + except TypeError as e: + print(e) + + elif choice == '4': + print("Exiting the program.") + break + + else: + print("Invalid choice. Please choose a valid option.") + +if __name__ == "__main__": + main() diff --git a/exercises/in_memory_db_persistent.py b/exercises/in_memory_db_persistent.py new file mode 100755 index 0000000..e4cb435 --- /dev/null +++ b/exercises/in_memory_db_persistent.py @@ -0,0 +1,104 @@ +# To make the program interactive and persistent, +# you can use a loop to continuously prompt the user for operations until they decide to exit. +# The problem requires implementing an in-memory key-value store +# where you can set a key-value pair and +# retrieve the value of a key. + +# Example: +# db.set(101, ["Sanjeev", "ProdSec"]) +# db.set(102, ["Deep", "DevSecOps"]) +# db.get(102) +# Think of command line for n inputs, set for n inputs, then based on command implement get, delete +# Example: +# Choose below options for operations: +# 1. set/create entries +# How many entries: 2 +# emp_id: input +# emp_details: input([]) +# 2. get emp_id details +# 3. delete emp_id details +# 4. update emp_id details + +class DB: + def __init__(self): + self.dic = {} + + def set(self, key: int, value: list) -> None: + if not isinstance(key, int): + raise TypeError("Key must be an integer") + if not isinstance(value, list): + raise TypeError("Value must be a list") + if key in self.dic: + raise ValueError(f"Key {key} already exists") + self.dic[key] = value + + def get(self, key: int) -> list: + if not isinstance(key, int): + raise TypeError("Key must be an integer") + if key in self.dic: + return self.dic[key] + else: + print(f"No record found for emp id: {key}") + return None + + def delete(self, key: int) -> None: + if not isinstance(key, int): + raise TypeError("Key must be an integer") + if key in self.dic: + print(f"Deleting emp id {key} details: {self.dic[key]}") + del self.dic[key] + print(f"Emp id {key} deleted successfully.") + else: + print(f"No record found for emp id: {key}") + print(f"Current employee list: {self.dic}") + +def main(): + db = DB() + db.set(101, ["Jassi", "ProdSec"]) + db.set(102, ["Deep", "DevSecOps"]) + db.set(103, ["Deepraj Barman", "Developer"]) + db.set(104, ["Himanshu", "AppSec"]) + + while True: + print("\nChoose an operation:") + print("1. Set a new entry") + print("2. Get an entry") + print("3. Delete an entry") + print("4. Exit") + + choice = input("Enter your choice (1/2/3/4): ") + + if choice == '1': + try: + key = int(input("Enter key (employee ID): ")) + value = input("Enter value (employee details separated by spaces): ").split() + db.set(key, value) + print(f"Set key {key} with value {value}") + except (TypeError, ValueError) as e: + print(e) + + elif choice == '2': + try: + key = int(input("Enter key (employee ID): ")) + details = db.get(key) + if details: + print(f"Emp id {key} details: {details}") + except TypeError as e: + print(e) + + elif choice == '3': + try: + key = int(input("Enter key (employee ID): ")) + db.delete(key) + except TypeError as e: + print(e) + + elif choice == '4': + print("Exiting the program.") + break + + else: + print("Invalid choice. Please choose a valid option.") + +if __name__ == "__main__": + main() diff --git a/exercises/requirements.txt b/exercises/requirements.txt new file mode 100644 index 0000000..6d87b75 --- /dev/null +++ b/exercises/requirements.txt @@ -0,0 +1,91 @@ +annotated-types==0.7.0 +anyio==3.7.1 +cairocffi==1.7.1 +CairoSVG==2.7.1 +certifi==2024.7.4 +cffi==1.16.0 +charset-normalizer==2.0.12 +click==8.1.7 +contourpy==1.2.1 +cryptography==43.0.0 +cssselect2==0.7.0 +cycler==0.12.1 +defusedxml==0.7.1 +easygui==0.98.3 +Faker==26.0.0 +fastapi==0.109.1 +Flask==2.2.5 +fonttools==4.53.1 +idna==3.7 +itsdangerous==2.2.0 +Jinja2==3.1.4 +kiwisolver==1.4.5 +looseversion==1.3.0 +MarkupSafe==2.1.5 +matplotlib==3.9.1 +numpy==2.0.1 +opencv-python==4.10.0.84 +packaging==24.1 +pafy==0.5.5 +pillow==10.4.0 +py-avataaars==1.1.2 +pycparser==2.22 +pydantic==1.10.17 +pydantic_core==2.20.1 +pyobjc-core==10.3.1 +pyobjc-framework-AudioVideoBridging==10.3.1 +pyobjc-framework-AVFoundation==10.3.1 +pyobjc-framework-AVRouting==10.3.1 +pyobjc-framework-BackgroundAssets==10.3.1 +pyobjc-framework-BrowserEngineKit==10.3.1 +pyobjc-framework-Cinematic==10.3.1 +pyobjc-framework-Cocoa==10.3.1 +pyobjc-framework-CoreAudio==10.3.1 +pyobjc-framework-CoreMedia==10.3.1 +pyobjc-framework-DataDetection==10.3.1 +pyobjc-framework-ExtensionKit==10.3.1 +pyobjc-framework-HealthKit==10.3.1 +pyobjc-framework-Intents==10.3.1 +pyobjc-framework-IntentsUI==10.3.1 +pyobjc-framework-IOBluetooth==10.3.1 +pyobjc-framework-IOBluetoothUI==10.3.1 +pyobjc-framework-libxpc==10.3.1 +pyobjc-framework-LocalAuthentication==10.3.1 +pyobjc-framework-LocalAuthenticationEmbeddedUI==10.3.1 +pyobjc-framework-MailKit==10.3.1 +pyobjc-framework-Metal==10.3.1 +pyobjc-framework-MetalFX==10.3.1 +pyobjc-framework-MetricKit==10.3.1 +pyobjc-framework-PHASE==10.3.1 +pyobjc-framework-Quartz==10.3.1 +pyobjc-framework-SafetyKit==10.3.1 +pyobjc-framework-ScreenCaptureKit==10.3.1 +pyobjc-framework-Security==10.3.1 +pyobjc-framework-SensitiveContentAnalysis==10.3.1 +pyobjc-framework-SharedWithYou==10.3.1 +pyobjc-framework-SharedWithYouCore==10.3.1 +pyobjc-framework-ShazamKit==10.3.1 +pyobjc-framework-Symbols==10.3.1 +pyobjc-framework-ThreadNetwork==10.3.1 +pyparsing==3.1.2 +pyshorteners==1.0.1 +python-dateutil==2.9.0.post0 +python-multipart==0.0.7 +python-nmap==0.7.1 +python3-nmap==1.6.0 +python_avatars==1.4.1 +PythonTurtle==0.3.2 +regex==2024.5.15 +requests==2.32.3 +simplejson==3.19.2 +six==1.16.0 +sniffio==1.3.1 +speech==0.5.2 +starlette==0.35.1 +tinycss2==1.3.0 +typing_extensions==4.12.2 +tzdata==2024.1 +urllib3==2.2.2 +webencodings==0.5.1 +Werkzeug==3.0.3 +youtube-dl==2021.12.17