diff --git a/.vscode/launch.json b/.vscode/launch.json index 67486cf1..6aeec48c 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -1,6 +1,34 @@ { "version": "0.2.0", "configurations": [ + { + "type": "java", + "name": "ArmstrongInRange", + "request": "launch", + "mainClass": "ArmstrongInRange", + "projectName": "programming-language_a42f5194" + }, + { + "type": "java", + "name": "PalindromeNumber", + "request": "launch", + "mainClass": "PalindromeNumber", + "projectName": "programming-language_a42f5194" + }, + { + "type": "java", + "name": "LargestInArray", + "request": "launch", + "mainClass": "LargestInArray", + "projectName": "programming-language_a42f5194" + }, + { + "type": "java", + "name": "PerfectNumber", + "request": "launch", + "mainClass": "PerfectNumber", + "projectName": "programming-language_a42f5194" + }, { "type": "java", "name": "ArmstrongNumber", diff --git a/AI_Chatbot/README.md b/AI_Chatbot/README.md new file mode 100644 index 00000000..15cf38f6 --- /dev/null +++ b/AI_Chatbot/README.md @@ -0,0 +1,82 @@ +# AI Chatbot - Intelligent Conversational Assistant + +A powerful and interactive AI chatbot built with Python that can engage in meaningful conversations and provide various helpful services. + +## Features + +- šŸ¤– **Intelligent Conversations**: Natural language processing for engaging dialogue +- šŸŒ¤ļø **Weather Information**: Get current weather for any city +- 🧮 **Mathematical Calculations**: Safe evaluation of mathematical expressions +- šŸ˜„ **Entertainment**: Tell jokes and stories +- šŸ’» **Programming Help**: Get tips and advice for coding +- ā° **Time & Date**: Current time and date information +- šŸ’¾ **Conversation History**: Save and recall previous conversations +- šŸŽÆ **Context Awareness**: Remembers user name and conversation flow + +## Installation + +```bash +# Clone the repository +git clone +cd AI_Chatbot + +# Install required dependencies +pip install requests datetime random json re math +``` + +## Usage + +```bash +python chatbot.py +``` + +## Example Conversations + +``` +You: Hello! +AI Assistant: Nice to meet you, John! Hello! I'm your AI assistant. How can I help you today? + +You: What's the weather in Jakarta? +AI Assistant: The weather in Jakarta is: Sunny, 32°C + +You: Calculate 15 * 8 + 32 +AI Assistant: The result is: 152 + +You: Tell me a joke +AI Assistant: Why don't scientists trust atoms? Because they make up everything! + +You: What time is it? +AI Assistant: Current time: 14:30:25, Date: 2024-01-15 +``` + +## Commands + +- **Greetings**: "hello", "hi", "hey", "good morning" +- **Weather**: "weather in [city]", "what's the weather" +- **Math**: "calculate [expression]", "what is 5 + 3" +- **Jokes**: "tell me a joke", "make me laugh" +- **Stories**: "tell me a story", "narrative" +- **Programming**: "programming help", "coding tips" +- **Time**: "what time is it", "current date" +- **Exit**: "quit", "exit", "bye" + +## Technical Details + +- **Language**: Python 3 +- **Architecture**: Object-oriented design with modular components +- **Safety**: Secure mathematical expression evaluation +- **Extensibility**: Easy to add new features and responses +- **Error Handling**: Robust error handling and graceful degradation + +## Contributing + +Feel free to contribute by: +- Adding new conversation topics +- Improving natural language processing +- Adding new features +- Fixing bugs +- Improving documentation + +## License + +This project is open source and available under the MIT License. diff --git a/AI_Chatbot/chatbot.py b/AI_Chatbot/chatbot.py new file mode 100644 index 00000000..70a8106d --- /dev/null +++ b/AI_Chatbot/chatbot.py @@ -0,0 +1,232 @@ +#!/usr/bin/env python3 +""" +AI Chatbot - Intelligent Conversational Assistant +================================================= + +A simple yet powerful AI chatbot that can: +- Answer questions intelligently +- Provide weather information +- Calculate mathematical expressions +- Tell jokes and stories +- Help with programming concepts +- Remember conversation context + +Author: AI Assistant +Language: Python 3 +Dependencies: requests, datetime, random, json +""" + +import json +import random +import datetime +import requests +import re +import math + +class AIChatbot: + def __init__(self): + self.name = "AI Assistant" + self.conversation_history = [] + self.user_name = "" + + # Knowledge base + self.responses = { + "greeting": [ + "Hello! I'm your AI assistant. How can I help you today?", + "Hi there! What would you like to know?", + "Greetings! I'm here to assist you with anything you need.", + "Hello! Ready to chat and help you out!" + ], + "farewell": [ + "Goodbye! It was nice talking to you!", + "See you later! Feel free to come back anytime.", + "Take care! Have a great day!", + "Farewell! Remember, I'm always here to help." + ], + "jokes": [ + "Why don't scientists trust atoms? Because they make up everything!", + "Why did the scarecrow win an award? He was outstanding in his field!", + "What do you call a fake noodle? An impasta!", + "Why don't eggs tell jokes? They'd crack each other up!", + "What do you call a bear with no teeth? A gummy bear!" + ], + "programming_tips": [ + "Always write clean, readable code with meaningful variable names.", + "Comment your code - your future self will thank you!", + "Test your code thoroughly before deploying.", + "Use version control (Git) for all your projects.", + "Learn one programming language deeply before moving to others." + ] + } + + def get_weather(self, city="Jakarta"): + """Get weather information for a city""" + try: + # Using a free weather API (OpenWeatherMap) + api_key = "demo_key" # Replace with actual API key + url = f"http://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}&units=metric" + + # For demo purposes, return mock data + mock_weather = { + "Jakarta": "Sunny, 32°C", + "Bandung": "Cloudy, 28°C", + "Surabaya": "Rainy, 26°C", + "Yogyakarta": "Partly cloudy, 30°C" + } + + return f"The weather in {city} is: {mock_weather.get(city, 'Weather data not available')}" + except: + return "Sorry, I couldn't fetch weather data right now." + + def calculate_math(self, expression): + """Safely evaluate mathematical expressions""" + try: + # Remove dangerous functions and only allow safe math operations + safe_dict = { + "__builtins__": {}, + "abs": abs, "round": round, "min": min, "max": max, + "sum": sum, "pow": pow, "sqrt": math.sqrt, + "sin": math.sin, "cos": math.cos, "tan": math.tan, + "log": math.log, "pi": math.pi, "e": math.e + } + + # Clean the expression + expression = re.sub(r'[^0-9+\-*/().\s]', '', expression) + result = eval(expression, safe_dict) + return f"The result is: {result}" + except: + return "Sorry, I couldn't calculate that. Please check your math expression." + + def tell_story(self): + """Tell a random short story""" + stories = [ + "Once upon a time, there was a little robot who dreamed of becoming a painter. Every day, it would collect colorful data and create beautiful digital art. The robot's art became so popular that it inspired humans to see the world in new ways.", + "In a distant galaxy, there lived a wise alien who could speak every programming language in the universe. One day, it met a curious human programmer, and together they created the most efficient algorithm ever known.", + "There was a magical computer that could solve any problem, but it had one condition: you had to ask the right question. Many tried, but only those who understood the problem deeply could unlock its power." + ] + return random.choice(stories) + + def process_message(self, user_input): + """Process user input and generate appropriate response""" + user_input = user_input.lower().strip() + + # Store conversation + self.conversation_history.append(f"User: {user_input}") + + # Greeting detection + if any(word in user_input for word in ["hello", "hi", "hey", "good morning", "good afternoon"]): + if not self.user_name: + self.user_name = input("What's your name? ") + return f"Nice to meet you, {self.user_name}! " + random.choice(self.responses["greeting"]) + return random.choice(self.responses["greeting"]) + + # Farewell detection + if any(word in user_input for word in ["bye", "goodbye", "see you", "farewell"]): + return random.choice(self.responses["farewell"]) + + # Weather request + if "weather" in user_input: + city = "Jakarta" # Default city + words = user_input.split() + for i, word in enumerate(words): + if word == "in" and i + 1 < len(words): + city = words[i + 1].capitalize() + return self.get_weather(city) + + # Math calculation + if any(op in user_input for op in ["+", "-", "*", "/", "calculate", "math", "="]): + # Extract mathematical expression + math_pattern = r'[\d+\-*/().\s]+' + match = re.search(math_pattern, user_input) + if match: + expression = match.group().strip() + return self.calculate_math(expression) + + # Joke request + if any(word in user_input for word in ["joke", "funny", "laugh"]): + return random.choice(self.responses["jokes"]) + + # Story request + if any(word in user_input for word in ["story", "tell me", "narrative"]): + return self.tell_story() + + # Programming help + if any(word in user_input for word in ["programming", "code", "coding", "developer", "programmer"]): + return random.choice(self.responses["programming_tips"]) + + # Time and date + if any(word in user_input for word in ["time", "date", "what time", "what date"]): + now = datetime.datetime.now() + return f"Current time: {now.strftime('%H:%M:%S')}, Date: {now.strftime('%Y-%m-%d')}" + + # Default responses + default_responses = [ + "That's interesting! Can you tell me more about that?", + "I'm not sure I understand. Could you rephrase that?", + "That's a great question! Let me think about it...", + "I'm learning new things every day. What else would you like to know?", + "Fascinating! I'd love to hear more about your thoughts on this." + ] + + return random.choice(default_responses) + + def chat(self): + """Main chat loop""" + print(f"šŸ¤– {self.name} is online!") + print("=" * 50) + print("Type 'quit' or 'exit' to end the conversation") + print("Try asking about weather, math, jokes, stories, or programming!") + print("=" * 50) + + while True: + try: + user_input = input("\nYou: ").strip() + + if user_input.lower() in ['quit', 'exit', 'bye']: + print(f"\n{self.name}: {random.choice(self.responses['farewell'])}") + break + + if not user_input: + continue + + response = self.process_message(user_input) + print(f"\n{self.name}: {response}") + + # Store bot response + self.conversation_history.append(f"Bot: {response}") + + except KeyboardInterrupt: + print(f"\n\n{self.name}: Goodbye! Thanks for chatting!") + break + except Exception as e: + print(f"\n{self.name}: Oops! Something went wrong: {e}") + + def save_conversation(self, filename="conversation_history.json"): + """Save conversation history to file""" + try: + with open(filename, 'w') as f: + json.dump(self.conversation_history, f, indent=2) + print(f"Conversation saved to {filename}") + except Exception as e: + print(f"Could not save conversation: {e}") + +def main(): + """Main function to run the chatbot""" + print("šŸš€ Starting AI Chatbot...") + + # Create and run chatbot + bot = AIChatbot() + bot.chat() + + # Ask if user wants to save conversation + try: + save = input("\nWould you like to save this conversation? (y/n): ").lower() + if save == 'y': + bot.save_conversation() + except: + pass + + print("\nšŸ‘‹ Thanks for using AI Chatbot!") + +if __name__ == "__main__": + main() diff --git a/C++ Code/heapSort.cpp b/C++ Code/heapSort.cpp new file mode 100644 index 00000000..4e20d122 --- /dev/null +++ b/C++ Code/heapSort.cpp @@ -0,0 +1,54 @@ +#include +using namespace std; + +// Maintains the max-heap property for subtree rooted at index i +void heapify(int arr[], int n, int i) +{ + int largest = i; // Assume current node is largest + int left = 2 * i + 1; // Left child index + int right = 2 * i + 2; // Right child index + + // If left child is larger than root + if (left < n && arr[left] > arr[largest]) + largest = left; + + // If right child is larger than current largest + if (right < n && arr[right] > arr[largest]) + largest = right; + + // If largest is not root, swap and continue heapifying + if (largest != i) + { + swap(arr[i], arr[largest]); + heapify(arr, n, largest); + } +} + +// Main function to perform Heap Sort +void heapSort(int arr[], int n) +{ + // Build max-heap + for (int i = n / 2 - 1; i >= 0; i--) + heapify(arr, n, i); + + // Extract elements from heap one by one + for (int i = n - 1; i >= 0; i--) + { + // Move current root (max element) to end + swap(arr[0], arr[i]); + // Call heapify on reduced heap + heapify(arr, i, 0); + } +} + +int main() +{ + int arr[] = {12, 11, 13, 5, 6, 7}; + int n = sizeof(arr) / sizeof(arr[0]); + + heapSort(arr, n); + + // Print sorted array + for (int i = 0; i < n; i++) + cout << arr[i] << " "; +} diff --git a/C/Tariff_Calculation.c b/C/Tariff_Calculation.c new file mode 100644 index 00000000..ebe06590 --- /dev/null +++ b/C/Tariff_Calculation.c @@ -0,0 +1,115 @@ +#include +#include + +struct Consumer { + char name[50]; + char type; + int time; + double energy; + double tariff; +}; + +void calculateTariff(struct Consumer *consumer) { + consumer->tariff = 0.0; + + if (consumer->type == 'D') { + consumer->tariff = 0.1 * consumer->energy; + } else if (consumer->type == 'I') { + consumer->tariff = 0.15 * consumer->energy; + } else { + printf("Invalid consumer type for %s.\n", consumer->name); + } + + if (consumer->time >= 9 && consumer->time <= 17) { + consumer->tariff += 0.05 * consumer->energy; + } else { + consumer->tariff += 0.03 * consumer->energy; + } +} + +int main() { + int numConsumers; + printf("Enter the number of consumers: "); + scanf("%d", &numConsumers); + + struct Consumer *consumers = (struct Consumer *)malloc(numConsumers * sizeof(struct Consumer)); + if (consumers == NULL) { + printf("Memory allocation failed. Exiting...\n"); + return 1; + } + + for (int i = 0; i < numConsumers; i++) { + printf("Enter consumer %d information:\n", i + 1); + printf("Name: "); + scanf("%s", consumers[i].name); + printf("Type (D for domestic, I for industrial): "); + scanf(" %c", &consumers[i].type); + printf("Time (in hours): "); + scanf("%d", &consumers[i].time); + printf("Energy consumed (in kWh): "); + scanf("%lf", &consumers[i].energy); + + calculateTariff(&consumers[i]); + } + + int choice; + while (1) { + printf("\nMenu:\n"); + printf("1. View Consumer Information\n"); + printf("2. Update Consumer Information\n"); + printf("3. Delete Consumer Information\n"); + printf("4. Exit\n"); + printf("Enter your choice: "); + scanf("%d", &choice); + + switch (choice) { + case 1: // View Consumer Information + printf("Enter the consumer number to view (1 to %d): ", numConsumers); + int viewIndex; + scanf("%d", &viewIndex); + if (viewIndex >= 1 && viewIndex <= numConsumers) { + struct Consumer consumer = consumers[viewIndex - 1]; + printf("Consumer Information:\n"); + printf("Name: %s, Type: %c, Tariff: $%.2lf\n", consumer.name, consumer.type, consumer.tariff); + } else { + printf("Invalid input. Please enter a valid consumer number.\n"); + } + break; + + case 2: // Update Consumer Information + printf("Enter the consumer number to update (1 to %d): ", numConsumers); + int updateIndex; + scanf("%d", &updateIndex); + if (updateIndex >= 1 && updateIndex <= numConsumers) { + struct Consumer *consumer = &consumers[updateIndex - 1]; + printf("Update Consumer Information for %s:\n", consumer->name); + // Prompt user to update fields like type, time, energy, etc. + // Then recalculate tariff using calculateTariff function. + } else { + printf("Invalid input. Please enter a valid consumer number.\n"); + } + break; + + case 3: // Delete Consumer Information + printf("Enter the consumer number to delete (1 to %d): ", numConsumers); + int deleteIndex; + scanf("%d", &deleteIndex); + if (deleteIndex >= 1 && deleteIndex <= numConsumers) { + // Implement code to delete the selected consumer, which may require shifting elements in the array. + // Be sure to free any memory if needed. + } else { + printf("Invalid input. Please enter a valid consumer number.\n"); + } + break; + + case 4: // Exit + free(consumers); // Free dynamically allocated memory + return 0; + + default: + printf("Invalid choice. Please select a valid option.\n"); + } + } + + return 0; +} diff --git a/File_Organizer/file_organizer.py b/File_Organizer/file_organizer.py new file mode 100644 index 00000000..b0dd5914 --- /dev/null +++ b/File_Organizer/file_organizer.py @@ -0,0 +1,432 @@ +#!/usr/bin/env python3 +""" +Smart File Organizer +==================== + +An intelligent file organization tool that automatically sorts and organizes +files based on their types, creation dates, and custom rules. + +Features: +- Automatic file type detection and sorting +- Custom organization rules and patterns +- Duplicate file detection and handling +- File metadata analysis +- Batch operations and scheduling +- Safe file operations with backup +- Progress tracking and logging +- GUI and command-line interfaces + +Author: AI Assistant +Language: Python 3 +Dependencies: os, shutil, pathlib, datetime, hashlib, json, logging +""" + +import os +import shutil +import hashlib +import json +import logging +from pathlib import Path +from datetime import datetime, timedelta +from collections import defaultdict +import mimetypes +import argparse +import sys + +class FileOrganizer: + def __init__(self, source_dir, destination_dir=None, dry_run=False): + self.source_dir = Path(source_dir) + self.destination_dir = Path(destination_dir) if destination_dir else self.source_dir + self.dry_run = dry_run + + # Setup logging + self.setup_logging() + + # File type mappings + self.file_types = { + 'images': ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.tiff', '.svg', '.webp', '.ico'], + 'videos': ['.mp4', '.avi', '.mkv', '.mov', '.wmv', '.flv', '.webm', '.m4v'], + 'audio': ['.mp3', '.wav', '.flac', '.aac', '.ogg', '.wma', '.m4a'], + 'documents': ['.pdf', '.doc', '.docx', '.txt', '.rtf', '.odt', '.xls', '.xlsx', '.ppt', '.pptx'], + 'archives': ['.zip', '.rar', '.7z', '.tar', '.gz', '.bz2'], + 'code': ['.py', '.js', '.html', '.css', '.java', '.cpp', '.c', '.php', '.rb', '.go'], + 'executables': ['.exe', '.msi', '.deb', '.rpm', '.dmg', '.app'], + 'fonts': ['.ttf', '.otf', '.woff', '.woff2'], + 'data': ['.json', '.xml', '.csv', '.sql', '.db', '.sqlite'] + } + + # Organization statistics + self.stats = { + 'files_processed': 0, + 'files_moved': 0, + 'files_copied': 0, + 'duplicates_found': 0, + 'errors': 0, + 'start_time': None, + 'end_time': None + } + + # Duplicate detection + self.file_hashes = {} + self.duplicates = [] + + def setup_logging(self): + """Setup logging configuration""" + log_filename = f"file_organizer_{datetime.now().strftime('%Y%m%d_%H%M%S')}.log" + logging.basicConfig( + level=logging.INFO, + format='%(asctime)s - %(levelname)s - %(message)s', + handlers=[ + logging.FileHandler(log_filename), + logging.StreamHandler(sys.stdout) + ] + ) + self.logger = logging.getLogger(__name__) + + def get_file_type(self, file_path): + """Determine file type based on extension and MIME type""" + file_path = Path(file_path) + extension = file_path.suffix.lower() + + # Check by extension first + for category, extensions in self.file_types.items(): + if extension in extensions: + return category + + # Check by MIME type + mime_type, _ = mimetypes.guess_type(str(file_path)) + if mime_type: + if mime_type.startswith('image/'): + return 'images' + elif mime_type.startswith('video/'): + return 'videos' + elif mime_type.startswith('audio/'): + return 'audio' + elif mime_type.startswith('text/'): + return 'documents' + + return 'other' + + def calculate_file_hash(self, file_path): + """Calculate MD5 hash of file for duplicate detection""" + try: + hash_md5 = hashlib.md5() + with open(file_path, "rb") as f: + for chunk in iter(lambda: f.read(4096), b""): + hash_md5.update(chunk) + return hash_md5.hexdigest() + except Exception as e: + self.logger.error(f"Error calculating hash for {file_path}: {e}") + return None + + def find_duplicates(self, files): + """Find duplicate files based on hash comparison""" + self.logger.info("Scanning for duplicate files...") + + for file_path in files: + file_hash = self.calculate_file_hash(file_path) + if file_hash: + if file_hash in self.file_hashes: + # Duplicate found + original_file = self.file_hashes[file_hash] + self.duplicates.append({ + 'original': original_file, + 'duplicate': file_path, + 'hash': file_hash, + 'size': file_path.stat().st_size + }) + self.stats['duplicates_found'] += 1 + else: + self.file_hashes[file_hash] = file_path + + self.logger.info(f"Found {len(self.duplicates)} duplicate files") + return self.duplicates + + def organize_by_type(self, files): + """Organize files by their type""" + self.logger.info("Organizing files by type...") + + for file_path in files: + try: + file_type = self.get_file_type(file_path) + destination_folder = self.destination_dir / file_type + + # Create destination folder if it doesn't exist + if not self.dry_run: + destination_folder.mkdir(parents=True, exist_ok=True) + + # Generate destination path + destination_path = destination_folder / file_path.name + + # Handle name conflicts + counter = 1 + original_destination = destination_path + while destination_path.exists(): + stem = original_destination.stem + suffix = original_destination.suffix + destination_path = destination_folder / f"{stem}_{counter}{suffix}" + counter += 1 + + # Move or copy file + if not self.dry_run: + shutil.move(str(file_path), str(destination_path)) + self.logger.info(f"Moved: {file_path} -> {destination_path}") + else: + self.logger.info(f"[DRY RUN] Would move: {file_path} -> {destination_path}") + + self.stats['files_moved'] += 1 + + except Exception as e: + self.logger.error(f"Error organizing {file_path}: {e}") + self.stats['errors'] += 1 + + self.stats['files_processed'] += 1 + + def organize_by_date(self, files): + """Organize files by creation date""" + self.logger.info("Organizing files by date...") + + for file_path in files: + try: + # Get file creation time + creation_time = datetime.fromtimestamp(file_path.stat().st_ctime) + date_folder = creation_time.strftime('%Y-%m-%d') + + destination_folder = self.destination_dir / 'by_date' / date_folder + + # Create destination folder if it doesn't exist + if not self.dry_run: + destination_folder.mkdir(parents=True, exist_ok=True) + + # Generate destination path + destination_path = destination_folder / file_path.name + + # Handle name conflicts + counter = 1 + original_destination = destination_path + while destination_path.exists(): + stem = original_destination.stem + suffix = original_destination.suffix + destination_path = destination_folder / f"{stem}_{counter}{suffix}" + counter += 1 + + # Move file + if not self.dry_run: + shutil.move(str(file_path), str(destination_path)) + self.logger.info(f"Moved: {file_path} -> {destination_path}") + else: + self.logger.info(f"[DRY RUN] Would move: {file_path} -> {destination_path}") + + self.stats['files_moved'] += 1 + + except Exception as e: + self.logger.error(f"Error organizing {file_path}: {e}") + self.stats['errors'] += 1 + + self.stats['files_processed'] += 1 + + def organize_by_size(self, files): + """Organize files by size ranges""" + self.logger.info("Organizing files by size...") + + size_ranges = { + 'tiny': (0, 1024), # < 1KB + 'small': (1024, 1024*1024), # 1KB - 1MB + 'medium': (1024*1024, 10*1024*1024), # 1MB - 10MB + 'large': (10*1024*1024, 100*1024*1024), # 10MB - 100MB + 'huge': (100*1024*1024, float('inf')) # > 100MB + } + + for file_path in files: + try: + file_size = file_path.stat().st_size + + # Determine size category + size_category = 'other' + for category, (min_size, max_size) in size_ranges.items(): + if min_size <= file_size < max_size: + size_category = category + break + + destination_folder = self.destination_dir / 'by_size' / size_category + + # Create destination folder if it doesn't exist + if not self.dry_run: + destination_folder.mkdir(parents=True, exist_ok=True) + + # Generate destination path + destination_path = destination_folder / file_path.name + + # Handle name conflicts + counter = 1 + original_destination = destination_path + while destination_path.exists(): + stem = original_destination.stem + suffix = original_destination.suffix + destination_path = destination_folder / f"{stem}_{counter}{suffix}" + counter += 1 + + # Move file + if not self.dry_run: + shutil.move(str(file_path), str(destination_path)) + self.logger.info(f"Moved: {file_path} -> {destination_path}") + else: + self.logger.info(f"[DRY RUN] Would move: {file_path} -> {destination_path}") + + self.stats['files_moved'] += 1 + + except Exception as e: + self.logger.error(f"Error organizing {file_path}: {e}") + self.stats['errors'] += 1 + + self.stats['files_processed'] += 1 + + def clean_empty_folders(self): + """Remove empty folders after organization""" + self.logger.info("Cleaning up empty folders...") + + def remove_empty_dirs(path): + if not path.is_dir(): + return + + # Remove empty subdirectories first + for subdir in path.iterdir(): + if subdir.is_dir(): + remove_empty_dirs(subdir) + + # Remove current directory if empty + try: + if not any(path.iterdir()): + path.rmdir() + self.logger.info(f"Removed empty folder: {path}") + except OSError: + pass # Directory not empty or permission denied + + if not self.dry_run: + remove_empty_dirs(self.source_dir) + + def generate_report(self): + """Generate organization report""" + self.stats['end_time'] = datetime.now() + duration = self.stats['end_time'] - self.stats['start_time'] + + report = f""" +File Organization Report +======================== +Start Time: {self.stats['start_time']} +End Time: {self.stats['end_time']} +Duration: {duration} + +Statistics: +- Files Processed: {self.stats['files_processed']} +- Files Moved: {self.stats['files_moved']} +- Files Copied: {self.stats['files_copied']} +- Duplicates Found: {self.stats['duplicates_found']} +- Errors: {self.stats['errors']} + +Duplicate Files: +""" + + for dup in self.duplicates: + report += f"- {dup['duplicate']} (duplicate of {dup['original']})\n" + + return report + + def organize(self, mode='type', recursive=True, include_hidden=False): + """Main organization method""" + self.stats['start_time'] = datetime.now() + self.logger.info(f"Starting file organization in mode: {mode}") + + # Get all files + if recursive: + files = list(self.source_dir.rglob('*')) + else: + files = list(self.source_dir.iterdir()) + + # Filter files only (exclude directories) + files = [f for f in files if f.is_file()] + + # Filter hidden files if requested + if not include_hidden: + files = [f for f in files if not f.name.startswith('.')] + + self.logger.info(f"Found {len(files)} files to organize") + + # Find duplicates first + self.find_duplicates(files) + + # Organize files based on mode + if mode == 'type': + self.organize_by_type(files) + elif mode == 'date': + self.organize_by_date(files) + elif mode == 'size': + self.organize_by_size(files) + else: + self.logger.error(f"Unknown organization mode: {mode}") + return + + # Clean up empty folders + self.clean_empty_folders() + + # Generate and save report + report = self.generate_report() + self.logger.info(report) + + # Save report to file + report_file = f"organization_report_{datetime.now().strftime('%Y%m%d_%H%M%S')}.txt" + with open(report_file, 'w') as f: + f.write(report) + + self.logger.info(f"Report saved to: {report_file}") + +def main(): + """Main function with command line interface""" + parser = argparse.ArgumentParser(description='Smart File Organizer') + parser.add_argument('source_dir', help='Source directory to organize') + parser.add_argument('-d', '--destination', help='Destination directory (default: same as source)') + parser.add_argument('-m', '--mode', choices=['type', 'date', 'size'], + default='type', help='Organization mode') + parser.add_argument('--dry-run', action='store_true', + help='Show what would be done without actually moving files') + parser.add_argument('--no-recursive', action='store_true', + help='Do not process subdirectories') + parser.add_argument('--include-hidden', action='store_true', + help='Include hidden files') + + args = parser.parse_args() + + # Validate source directory + source_path = Path(args.source_dir) + if not source_path.exists(): + print(f"Error: Source directory '{args.source_dir}' does not exist") + sys.exit(1) + + if not source_path.is_dir(): + print(f"Error: '{args.source_dir}' is not a directory") + sys.exit(1) + + # Create organizer + organizer = FileOrganizer( + source_dir=args.source_dir, + destination_dir=args.destination, + dry_run=args.dry_run + ) + + # Run organization + try: + organizer.organize( + mode=args.mode, + recursive=not args.no_recursive, + include_hidden=args.include_hidden + ) + print("File organization completed successfully!") + except KeyboardInterrupt: + print("\nOperation cancelled by user") + sys.exit(1) + except Exception as e: + print(f"Error during organization: {e}") + sys.exit(1) + +if __name__ == "__main__": + main() diff --git a/Java/ArmstrongInRange.java b/Java/ArmstrongInRange.java new file mode 100644 index 00000000..6148f6c1 --- /dev/null +++ b/Java/ArmstrongInRange.java @@ -0,0 +1,21 @@ +import java.util.Scanner; + +public class ArmstrongInRange { + public static void main(String[] args) { + Scanner sc = new Scanner(System.in); + System.out.print("Enter start: "); + int start = sc.nextInt(); + System.out.print("Enter end: "); + int end = sc.nextInt(); + System.out.println("Armstrong numbers between " + start + " and " + end + ":"); + for (int num = start; num <= end; num++) { + int sum = 0, temp = num, digits = String.valueOf(num).length(); + while (temp > 0) { + sum += Math.pow(temp % 10, digits); + temp /= 10; + } + if (sum == num) System.out.print(num + " "); + } + sc.close(); + } +} diff --git a/Java/LargestInArray.java b/Java/LargestInArray.java new file mode 100644 index 00000000..9e6b32e2 --- /dev/null +++ b/Java/LargestInArray.java @@ -0,0 +1,16 @@ +import java.util.Scanner; + +public class LargestInArray { + public static void main(String[] args) { + Scanner sc = new Scanner(System.in); + System.out.print("Enter number of elements: "); + int n = sc.nextInt(); + int[] arr = new int[n]; + System.out.println("Enter elements:"); + for (int i = 0; i < n; i++) arr[i] = sc.nextInt(); + int max = arr[0]; + for (int num : arr) if (num > max) max = num; + System.out.println("Largest element: " + max); + sc.close(); + } +} diff --git a/Java/PalindromeNumber.java b/Java/PalindromeNumber.java new file mode 100644 index 00000000..5c8e284b --- /dev/null +++ b/Java/PalindromeNumber.java @@ -0,0 +1,19 @@ +import java.util.Scanner; + +public class PalindromeNumber { + public static void main(String[] args) { + Scanner sc = new Scanner(System.in); + System.out.print("Enter a number: "); + int num = sc.nextInt(); + int original = num, rev = 0; + while (num != 0) { + rev = rev * 10 + num % 10; + num /= 10; + } + if (rev == original) + System.out.println(original + " is a palindrome number!"); + else + System.out.println(original + " is NOT a palindrome number."); + sc.close(); + } +} diff --git a/Java/PerfectNumber.java b/Java/PerfectNumber.java new file mode 100644 index 00000000..3849e5ae --- /dev/null +++ b/Java/PerfectNumber.java @@ -0,0 +1,18 @@ +import java.util.Scanner; + +public class PerfectNumber { + public static void main(String[] args) { + Scanner sc = new Scanner(System.in); + System.out.print("Enter a number: "); + int num = sc.nextInt(); + int sum = 0; + for (int i = 1; i <= num / 2; i++) { + if (num % i == 0) sum += i; + } + if (sum == num) + System.out.println(num + " is a Perfect Number."); + else + System.out.println(num + " is NOT a Perfect Number."); + sc.close(); + } +} diff --git a/Password_Generator/README.md b/Password_Generator/README.md new file mode 100644 index 00000000..963de7bb --- /dev/null +++ b/Password_Generator/README.md @@ -0,0 +1,165 @@ +# Advanced Password Generator šŸ” + +A comprehensive and secure password generator that creates strong, customizable passwords with advanced security features and analysis capabilities. + +## Features + +- šŸ”’ **Secure Generation**: Uses cryptographically secure random number generation +- šŸŽÆ **Customizable Options**: Control length, character sets, and requirements +- šŸ“Š **Strength Analysis**: Detailed password strength evaluation and feedback +- 🧠 **Passphrase Generation**: Create memorable passphrases using common words +- šŸ“ˆ **Bulk Generation**: Generate multiple passwords at once +- šŸ“ **Password History**: Track generated passwords with timestamps +- šŸ’¾ **Export Functionality**: Save password history to files +- šŸ” **Pattern Detection**: Identifies common weak patterns +- šŸ“Š **Entropy Calculation**: Measures password randomness and security + +## Installation + +```bash +# Clone the repository +git clone +cd Password_Generator + +# No external dependencies required - uses only Python standard library +python password_generator.py +``` + +## Usage + +### Interactive Mode +```bash +python password_generator.py +``` + +### Programmatic Usage +```python +from password_generator import PasswordGenerator + +# Create generator instance +generator = PasswordGenerator() + +# Generate a secure password +password = generator.generate_password( + length=16, + include_uppercase=True, + include_lowercase=True, + include_digits=True, + include_symbols=True, + min_uppercase=2, + min_lowercase=2, + min_digits=2, + min_symbols=2 +) + +# Analyze password strength +analysis = generator.analyze_password_strength(password) +print(f"Password: {password}") +print(f"Strength: {analysis['strength']}") +print(f"Score: {analysis['score']}/8") +``` + +## Password Generation Options + +### Single Password +- **Length**: 8-128 characters (default: 12) +- **Character Sets**: Uppercase, lowercase, digits, symbols +- **Minimum Requirements**: Set minimum counts for each character type +- **Exclusions**: Remove similar/ambiguous characters + +### Passphrase Generation +- **Word Count**: 3-10 words (default: 4) +- **Separators**: Custom separators between words +- **Capitalization**: Optional word capitalization +- **Numbers & Symbols**: Optional random additions + +### Bulk Generation +- Generate multiple passwords with same settings +- Useful for creating password lists +- Maintains individual password strength + +## Password Strength Analysis + +The generator provides comprehensive strength analysis: + +- **Length Analysis**: Evaluates password length +- **Character Variety**: Checks for multiple character types +- **Pattern Detection**: Identifies common weak patterns +- **Entropy Calculation**: Measures randomness and security +- **Strength Levels**: Weak, Medium, Strong, Very Strong + +### Strength Scoring +- **0-1**: Weak (easily cracked) +- **2-3**: Medium (moderate security) +- **4-5**: Strong (good security) +- **6-8**: Very Strong (excellent security) + +## Security Features + +- **Cryptographically Secure**: Uses `secrets` module for true randomness +- **No Weak Patterns**: Avoids common patterns like "123", "abc", "qwerty" +- **Character Exclusions**: Option to exclude similar/ambiguous characters +- **Minimum Requirements**: Ensures password meets complexity requirements +- **Entropy Analysis**: Calculates and reports password entropy + +## Examples + +### Strong Password Generation +``` +Generated Password: K9#mP2$vL8@nQ4! +Strength: VERY_STRONG +Score: 8/8 +Entropy: 78.45 +``` + +### Passphrase Generation +``` +Generated Passphrase: Dragon-Sunset-Mountain-River-42! +Strength: STRONG +Score: 6/8 +``` + +### Bulk Generation +``` +Generated 5 passwords: + 1. mK7#nP9$vL2@qR5! + 2. X3&bN8*vM4@tS6# + 3. Q9$cF2#wH5@yU7! + 4. Z6&dG8*vJ3@kI4# + 5. L1$eH9#xK7@mN2! +``` + +## File Structure + +``` +Password_Generator/ +ā”œā”€ā”€ password_generator.py # Main generator class and functions +ā”œā”€ā”€ README.md # This documentation +└── requirements.txt # Dependencies (none required) +``` + +## Contributing + +Contributions are welcome! Areas for improvement: +- Additional character sets +- More sophisticated pattern detection +- Integration with password managers +- GUI interface +- Additional export formats +- Password policy validation + +## Security Notes + +- This tool generates passwords locally - no data is sent to external servers +- Password history is stored locally and can be exported +- Use strong, unique passwords for all accounts +- Consider using a password manager for long-term storage +- Regularly update passwords for critical accounts + +## License + +This project is open source and available under the MIT License. + +--- + +**Remember**: The best password is one that's both strong and memorable. Use this tool responsibly and never share your passwords! diff --git a/Password_Generator/password_generator.py b/Password_Generator/password_generator.py new file mode 100644 index 00000000..00dfbc5e --- /dev/null +++ b/Password_Generator/password_generator.py @@ -0,0 +1,463 @@ +#!/usr/bin/env python3 +""" +Advanced Password Generator +=========================== + +A comprehensive password generator that creates secure, customizable passwords +with various complexity levels and security features. + +Features: +- Multiple password generation strategies +- Customizable length and character sets +- Password strength analysis +- Secure random generation +- Password history and validation +- Export/import functionality + +Author: AI Assistant +Language: Python 3 +Dependencies: secrets, string, random, json, datetime +""" + +import secrets +import string +import random +import json +import datetime +import hashlib +import base64 + +class PasswordGenerator: + def __init__(self): + self.password_history = [] + self.strength_levels = { + "weak": 0, + "medium": 1, + "strong": 2, + "very_strong": 3 + } + + # Character sets + self.char_sets = { + "lowercase": string.ascii_lowercase, + "uppercase": string.ascii_uppercase, + "digits": string.digits, + "symbols": "!@#$%^&*()_+-=[]{}|;:,.<>?", + "extended": "~`!@#$%^&*()_+-=[]{}|;:,.<>?/\\\"'" + } + + def generate_password(self, length=12, include_uppercase=True, include_lowercase=True, + include_digits=True, include_symbols=True, exclude_similar=True, + exclude_ambiguous=True, min_uppercase=1, min_lowercase=1, + min_digits=1, min_symbols=1): + """ + Generate a secure password with specified requirements + + Args: + length (int): Password length + include_uppercase (bool): Include uppercase letters + include_lowercase (bool): Include lowercase letters + include_digits (bool): Include digits + include_symbols (bool): Include symbols + exclude_similar (bool): Exclude similar characters (0, O, l, 1) + exclude_ambiguous (bool): Exclude ambiguous characters + min_uppercase (int): Minimum uppercase letters required + min_lowercase (int): Minimum lowercase letters required + min_digits (int): Minimum digits required + min_symbols (int): Minimum symbols required + + Returns: + str: Generated password + """ + + # Build character pool + char_pool = "" + required_chars = [] + + if include_lowercase: + chars = self.char_sets["lowercase"] + if exclude_similar: + chars = chars.replace('l', '').replace('o', '') + if exclude_ambiguous: + chars = chars.replace('i', '').replace('j', '') + char_pool += chars + required_chars.extend(random.choices(chars, k=min_lowercase)) + + if include_uppercase: + chars = self.char_sets["uppercase"] + if exclude_similar: + chars = chars.replace('O', '').replace('I', '') + if exclude_ambiguous: + chars = chars.replace('I', '').replace('J', '') + char_pool += chars + required_chars.extend(random.choices(chars, k=min_uppercase)) + + if include_digits: + chars = self.char_sets["digits"] + if exclude_similar: + chars = chars.replace('0', '').replace('1', '') + char_pool += chars + required_chars.extend(random.choices(chars, k=min_digits)) + + if include_symbols: + chars = self.char_sets["symbols"] + if exclude_ambiguous: + chars = chars.replace('(', '').replace(')', '').replace('[', '').replace(']', '') + char_pool += chars + required_chars.extend(random.choices(chars, k=min_symbols)) + + if not char_pool: + raise ValueError("At least one character set must be included") + + # Generate remaining characters + remaining_length = length - len(required_chars) + if remaining_length < 0: + raise ValueError("Minimum requirements exceed password length") + + additional_chars = [secrets.choice(char_pool) for _ in range(remaining_length)] + + # Combine and shuffle + all_chars = required_chars + additional_chars + random.shuffle(all_chars) + + password = ''.join(all_chars) + + # Store in history + self._add_to_history(password) + + return password + + def generate_passphrase(self, word_count=4, separator="-", capitalize=True, + include_numbers=True, include_symbols=False): + """ + Generate a memorable passphrase using common words + + Args: + word_count (int): Number of words in passphrase + separator (str): Separator between words + capitalize (bool): Capitalize first letter of each word + include_numbers (bool): Include random numbers + include_symbols (bool): Include random symbols + + Returns: + str: Generated passphrase + """ + + # Common word list for passphrases + word_list = [ + "apple", "banana", "cherry", "dragon", "eagle", "forest", "garden", + "house", "island", "jungle", "knight", "ladder", "mountain", "ocean", + "palace", "queen", "river", "sunset", "tiger", "umbrella", "violet", + "window", "yellow", "zebra", "adventure", "beautiful", "creative", + "dancing", "electric", "fantastic", "guitar", "harmony", "incredible", + "journey", "knowledge", "laughter", "magical", "nature", "optimistic", + "peaceful", "quality", "rainbow", "sunshine", "treasure", "unique", + "victory", "wonderful", "excellent", "yesterday", "zealous" + ] + + # Select random words + words = random.sample(word_list, word_count) + + # Apply modifications + if capitalize: + words = [word.capitalize() for word in words] + + # Add numbers and symbols if requested + if include_numbers: + words.append(str(random.randint(10, 99))) + + if include_symbols: + symbols = "!@#$%^&*" + words.append(random.choice(symbols)) + + passphrase = separator.join(words) + + # Store in history + self._add_to_history(passphrase) + + return passphrase + + def analyze_password_strength(self, password): + """ + Analyze password strength and provide detailed feedback + + Args: + password (str): Password to analyze + + Returns: + dict: Analysis results + """ + + score = 0 + feedback = [] + + # Length analysis + length = len(password) + if length < 8: + feedback.append("Password is too short (minimum 8 characters recommended)") + elif length >= 12: + score += 2 + feedback.append("Good password length") + else: + score += 1 + + # Character variety analysis + has_lower = any(c.islower() for c in password) + has_upper = any(c.isupper() for c in password) + has_digit = any(c.isdigit() for c in password) + has_symbol = any(c in string.punctuation for c in password) + + char_types = sum([has_lower, has_upper, has_digit, has_symbol]) + + if char_types >= 4: + score += 3 + feedback.append("Excellent character variety") + elif char_types == 3: + score += 2 + feedback.append("Good character variety") + elif char_types == 2: + score += 1 + feedback.append("Consider adding more character types") + else: + feedback.append("Password uses only one character type") + + # Pattern analysis + if self._has_common_patterns(password): + score -= 1 + feedback.append("Avoid common patterns (123, abc, qwerty)") + + # Entropy calculation + entropy = self._calculate_entropy(password) + if entropy > 60: + score += 2 + feedback.append("High entropy - very secure") + elif entropy > 40: + score += 1 + feedback.append("Good entropy") + else: + feedback.append("Low entropy - consider more randomness") + + # Determine strength level + if score >= 6: + strength = "very_strong" + elif score >= 4: + strength = "strong" + elif score >= 2: + strength = "medium" + else: + strength = "weak" + + return { + "password": password, + "length": length, + "strength": strength, + "score": score, + "entropy": entropy, + "feedback": feedback, + "character_types": { + "lowercase": has_lower, + "uppercase": has_upper, + "digits": has_digit, + "symbols": has_symbol + } + } + + def _has_common_patterns(self, password): + """Check for common patterns in password""" + common_patterns = [ + "123", "abc", "qwerty", "password", "admin", "user", + "letmein", "welcome", "monkey", "dragon", "master" + ] + + password_lower = password.lower() + return any(pattern in password_lower for pattern in common_patterns) + + def _calculate_entropy(self, password): + """Calculate password entropy""" + char_set_size = 0 + + if any(c.islower() for c in password): + char_set_size += 26 + if any(c.isupper() for c in password): + char_set_size += 26 + if any(c.isdigit() for c in password): + char_set_size += 10 + if any(c in string.punctuation for c in password): + char_set_size += 32 + + if char_set_size == 0: + return 0 + + entropy = len(password) * (char_set_size ** 0.5) + return entropy + + def _add_to_history(self, password): + """Add password to history with metadata""" + entry = { + "password": password, + "timestamp": datetime.datetime.now().isoformat(), + "hash": hashlib.sha256(password.encode()).hexdigest()[:16] + } + self.password_history.append(entry) + + # Keep only last 50 passwords + if len(self.password_history) > 50: + self.password_history = self.password_history[-50:] + + def export_passwords(self, filename="password_export.json", include_passwords=True): + """Export password history to file""" + export_data = { + "export_date": datetime.datetime.now().isoformat(), + "total_passwords": len(self.password_history), + "passwords": [] + } + + for entry in self.password_history: + if include_passwords: + export_data["passwords"].append(entry) + else: + # Export only metadata without actual passwords + export_data["passwords"].append({ + "timestamp": entry["timestamp"], + "hash": entry["hash"] + }) + + with open(filename, 'w') as f: + json.dump(export_data, f, indent=2) + + return f"Exported {len(self.password_history)} passwords to {filename}" + + def generate_bulk_passwords(self, count=10, **kwargs): + """Generate multiple passwords at once""" + passwords = [] + for _ in range(count): + password = self.generate_password(**kwargs) + passwords.append(password) + return passwords + +def main(): + """Main function to run the password generator""" + print("šŸ” Advanced Password Generator") + print("=" * 50) + + generator = PasswordGenerator() + + while True: + print("\nOptions:") + print("1. Generate Single Password") + print("2. Generate Passphrase") + print("3. Generate Multiple Passwords") + print("4. Analyze Password Strength") + print("5. View Password History") + print("6. Export Passwords") + print("7. Exit") + + choice = input("\nEnter your choice (1-7): ").strip() + + if choice == "1": + try: + length = int(input("Password length (default 12): ") or "12") + include_upper = input("Include uppercase? (y/n, default y): ").lower() != 'n' + include_lower = input("Include lowercase? (y/n, default y): ").lower() != 'n' + include_digits = input("Include digits? (y/n, default y): ").lower() != 'n' + include_symbols = input("Include symbols? (y/n, default y): ").lower() != 'n' + + password = generator.generate_password( + length=length, + include_uppercase=include_upper, + include_lowercase=include_lower, + include_digits=include_digits, + include_symbols=include_symbols + ) + + print(f"\nGenerated Password: {password}") + + # Analyze strength + analysis = generator.analyze_password_strength(password) + print(f"Strength: {analysis['strength'].upper()}") + print(f"Score: {analysis['score']}/8") + print("Feedback:") + for feedback in analysis['feedback']: + print(f" - {feedback}") + + except ValueError as e: + print(f"Error: {e}") + + elif choice == "2": + try: + word_count = int(input("Number of words (default 4): ") or "4") + separator = input("Separator (default '-'): ") or "-" + capitalize = input("Capitalize words? (y/n, default y): ").lower() != 'n' + include_numbers = input("Include numbers? (y/n, default n): ").lower() == 'y' + include_symbols = input("Include symbols? (y/n, default n): ").lower() == 'y' + + passphrase = generator.generate_passphrase( + word_count=word_count, + separator=separator, + capitalize=capitalize, + include_numbers=include_numbers, + include_symbols=include_symbols + ) + + print(f"\nGenerated Passphrase: {passphrase}") + + except ValueError as e: + print(f"Error: {e}") + + elif choice == "3": + try: + count = int(input("Number of passwords to generate (default 10): ") or "10") + length = int(input("Password length (default 12): ") or "12") + + passwords = generator.generate_bulk_passwords(count=count, length=length) + + print(f"\nGenerated {count} passwords:") + for i, password in enumerate(passwords, 1): + print(f"{i:2d}. {password}") + + except ValueError as e: + print(f"Error: {e}") + + elif choice == "4": + password = input("Enter password to analyze: ").strip() + if password: + analysis = generator.analyze_password_strength(password) + print(f"\nPassword Analysis:") + print(f"Password: {analysis['password']}") + print(f"Length: {analysis['length']}") + print(f"Strength: {analysis['strength'].upper()}") + print(f"Score: {analysis['score']}/8") + print(f"Entropy: {analysis['entropy']:.2f}") + print("Character Types:") + for char_type, present in analysis['character_types'].items(): + status = "āœ“" if present else "āœ—" + print(f" {char_type}: {status}") + print("Feedback:") + for feedback in analysis['feedback']: + print(f" - {feedback}") + + elif choice == "5": + if generator.password_history: + print(f"\nPassword History ({len(generator.password_history)} entries):") + for i, entry in enumerate(generator.password_history[-10:], 1): + timestamp = datetime.datetime.fromisoformat(entry['timestamp']) + print(f"{i:2d}. {entry['password']} ({timestamp.strftime('%Y-%m-%d %H:%M')})") + else: + print("No passwords in history yet.") + + elif choice == "6": + include_passwords = input("Include actual passwords in export? (y/n, default n): ").lower() == 'y' + filename = input("Export filename (default password_export.json): ") or "password_export.json" + + result = generator.export_passwords(filename, include_passwords) + print(f"\n{result}") + + elif choice == "7": + print("Goodbye! Stay secure! šŸ”") + break + + else: + print("Invalid choice. Please try again.") + +if __name__ == "__main__": + main() diff --git a/Python/Voicebook.py b/Python/Voicebook.py new file mode 100644 index 00000000..9cd42e76 --- /dev/null +++ b/Python/Voicebook.py @@ -0,0 +1,59 @@ +import speech_recognition as sheru +import pyttsx3 +import pywhatkit +import wikipedia + +def Take_query(): + + + Hello() + + while(True): + + + query = takeCommand().lower() + if "open geeksforgeeks" in query: + speak("Opening GeeksforGeeks ") + + # in the open method we just to give the link + # of the website and it automatically open + # it in your default browser + webbrowser.open("www.geeksforgeeks.com") + continue + + elif "open google" in query: + speak("Opening Google ") + webbrowser.open("www.google.com") + continue + + elif "which day it is" in query: + tellDay() + continue + + elif "tell me the time" in query: + tellTime() + continue + + # this will exit and terminate the program + elif "bye" in query: + speak("Bye. Check Out GFG for more exicting things") + exit() + + elif "from wikipedia" in query: + + + speak("Checking the wikipedia ") + query = query.replace("wikipedia", "") + + # it will give the summary of 4 lines from + # wikipedia we can increase and decrease + # it also. + result = wikipedia.summary(query, sentences=4) + speak("According to wikipedia") + speak(result) + + elif "tell me your name" in query: + speak("I am Jarvis. Your deskstop Assistant") + +def speak(audio) +speak diff --git a/README.md b/README.md index cf550893..8384a8fa 100644 --- a/README.md +++ b/README.md @@ -2,15 +2,35 @@ Welcome to the Programming Language Projects repository! This repository is a collection of various web development projects implemented using a variety of web technologies, including Python, Java, CPP, and various Programming Languages. Whether you are a programmer, a DSA enthusiast, or a beginner, you'll find a diverse range of projects here to explore, learn from, and contribute to. +## Programming Language Algorithms + +A collection of algorithms implemented in JavaScript and Java. + ## Contributing -If you'd like to contribute to this repository, please refer to the contributing guidelines provided in the [CONTRIBUTING](CONTRIBUTING.md) file. We welcome your contributions and appreciate your help in making this repository even better! -We particularly appreciate well-documented and commented code to help others understand your work. +If you'd like to contribute to this repository, please refer to the contributing guidelines provided in the (CONTRIBUTING.md) file. We welcome your contributions and appreciate your help in making this repository even better! We particularly appreciate well-documented and commented code to help others understand your work. + +We welcome contributions from everyone, especially during Hacktoberfest! +To participate: + +1. Fork this repository. +2. Create a new branch for your changes. +3. Add your algorithm or improve existing ones. +4. Open a pull request. + +## Hacktoberfest + +This repository is open for Hacktoberfest contributions. +Please make sure your pull request follows our guidelines. ## Code of Conduct Please note that by contributing to this repository, you agree to abide by the [Code of Conduct](CODE_OF_CONDUCT.md). We expect all contributors to be respectful and considerate of others' work and opinions. Any violations of this code will not be tolerated. +## License + +MIT + ## Documentation Comprehensive documentation of your Programming Language projects is essential. Ensure you include detailed explanations of your project's algorithm, architecture, features, and how to set up and run it. Comment your code effectively to assist others in understanding your implementation. A clear README is crucial to help users and contributors get started with your project. diff --git a/Snake_Game/README.md b/Snake_Game/README.md new file mode 100644 index 00000000..20c89104 --- /dev/null +++ b/Snake_Game/README.md @@ -0,0 +1,170 @@ +# Snake Game - Classic Arcade Experience šŸ + +A modern, feature-rich implementation of the classic Snake game built with Python and Pygame. Experience the nostalgia of arcade gaming with enhanced graphics, multiple difficulty levels, and smooth gameplay. + +## Features + +- šŸŽ® **Classic Gameplay**: Traditional Snake game mechanics with modern enhancements +- šŸŽÆ **Multiple Difficulty Levels**: Easy, Medium, and Hard modes +- šŸ† **Score System**: Track your score and compete for high scores +- šŸ“Š **Level Progression**: Speed increases as you advance through levels +- šŸŽ **Special Food Types**: Normal, bonus, and special food with different point values +- āøļø **Pause Functionality**: Pause and resume gameplay anytime +- šŸŽØ **Beautiful Graphics**: Smooth animations and colorful visuals +- šŸ’¾ **High Score Persistence**: Your best scores are saved automatically +- šŸŽµ **Sound Effects**: Optional audio feedback (can be extended) + +## Installation + +### Prerequisites +- Python 3.6 or higher +- Pygame library + +### Setup +```bash +# Clone the repository +git clone +cd Snake_Game + +# Install Pygame +pip install pygame + +# Run the game +python snake_game.py +``` + +### Alternative Installation +```bash +# Using pip with requirements +pip install -r requirements.txt +python snake_game.py +``` + +## How to Play + +### Basic Controls +- **Arrow Keys** or **WASD**: Move the snake +- **Space**: Pause/Resume game +- **ESC**: Return to main menu or exit +- **R**: Restart game (when game over) +- **H**: View high scores + +### Game Rules +1. Control the snake to eat food and grow longer +2. Avoid hitting walls or your own body +3. Different food types give different points: + - **Red Food**: 10 points (normal) + - **Yellow Food**: 25 points (bonus) + - **Purple Food**: 50 points (special) +4. Speed increases every 50 points (new level) +5. Try to achieve the highest score possible! + +### Difficulty Levels +- **Easy**: Slower speed, more forgiving gameplay +- **Medium**: Balanced speed and challenge (default) +- **Hard**: Faster speed, more challenging gameplay + +## Game Features + +### Visual Elements +- **Snake Head**: Dark green with white border +- **Snake Body**: Bright green segments +- **Food Types**: Different colors and effects +- **UI Elements**: Score, high score, level display +- **Smooth Animations**: Fluid movement and transitions + +### Scoring System +- **Normal Food**: 10 points +- **Bonus Food**: 25 points +- **Special Food**: 50 points +- **Level Bonus**: Speed increases every 50 points +- **High Score**: Automatically saved and displayed + +### Game States +- **Main Menu**: Choose difficulty and view options +- **Playing**: Active gameplay +- **Paused**: Game paused, can resume +- **Game Over**: Final score and restart options +- **High Scores**: View your best performance + +## Technical Details + +### Architecture +- **Object-Oriented Design**: Clean, modular code structure +- **State Management**: Proper game state handling +- **Event-Driven**: Responsive input handling +- **Performance Optimized**: Smooth 60 FPS gameplay + +### File Structure +``` +Snake_Game/ +ā”œā”€ā”€ snake_game.py # Main game file +ā”œā”€ā”€ README.md # This documentation +ā”œā”€ā”€ requirements.txt # Dependencies +└── high_score.json # High score storage (auto-generated) +``` + +### Dependencies +- **pygame**: Game development library +- **json**: High score persistence +- **random**: Food placement +- **sys**: System operations +- **os**: File operations + +## Customization + +### Easy Modifications +- **Colors**: Change color scheme in constants section +- **Speed**: Adjust initial speed and level progression +- **Grid Size**: Modify GRID_SIZE for different resolutions +- **Food Types**: Add new food types with custom behaviors +- **Scoring**: Adjust point values for different food types + +### Advanced Customization +- **Sound Effects**: Add audio with pygame.mixer +- **Power-ups**: Implement special abilities +- **Multiplayer**: Add two-player mode +- **Themes**: Create different visual themes +- **Mobile Support**: Adapt for touch controls + +## Troubleshooting + +### Common Issues +1. **Pygame not found**: Install with `pip install pygame` +2. **Game runs too fast/slow**: Adjust speed settings in code +3. **Controls not responsive**: Check for conflicting key mappings +4. **High score not saving**: Ensure write permissions in game directory + +### Performance Tips +- Close other applications for better performance +- Use fullscreen mode for smoother gameplay +- Adjust speed settings if game feels sluggish + +## Contributing + +Contributions are welcome! Areas for improvement: +- **New Features**: Power-ups, obstacles, multiplayer +- **Visual Enhancements**: Better graphics, animations, effects +- **Audio**: Sound effects and background music +- **Mobile Support**: Touch controls and mobile optimization +- **AI Mode**: Computer-controlled snake opponent +- **Level Editor**: Custom level creation tools + +## Future Enhancements + +- **Multiplayer Mode**: Local and online multiplayer +- **Power-ups**: Speed boost, invincibility, score multiplier +- **Obstacles**: Walls and barriers to navigate +- **Themes**: Multiple visual themes and skins +- **Achievements**: Unlockable achievements and rewards +- **Statistics**: Detailed gameplay statistics and analytics + +## License + +This project is open source and available under the MIT License. + +--- + +**Enjoy the classic Snake experience with modern enhancements!** šŸšŸŽ® + +Try to beat your high score and challenge your friends! diff --git a/Snake_Game/requirements.txt b/Snake_Game/requirements.txt new file mode 100644 index 00000000..5d2caa22 --- /dev/null +++ b/Snake_Game/requirements.txt @@ -0,0 +1 @@ +pygame>=2.0.0 diff --git a/Snake_Game/snake_game.py b/Snake_Game/snake_game.py new file mode 100644 index 00000000..33999d8d --- /dev/null +++ b/Snake_Game/snake_game.py @@ -0,0 +1,488 @@ +#!/usr/bin/env python3 +""" +Snake Game - Classic Arcade Game +================================ + +A modern implementation of the classic Snake game with enhanced features: +- Smooth gameplay with customizable speed +- Score tracking and high score system +- Multiple difficulty levels +- Beautiful graphics and animations +- Sound effects (optional) +- Pause functionality +- Game over screen with restart option + +Author: AI Assistant +Language: Python 3 +Dependencies: pygame, random, sys, os +""" + +import pygame +import random +import sys +import os +import json +from enum import Enum + +# Initialize Pygame +pygame.init() + +# Constants +WINDOW_WIDTH = 800 +WINDOW_HEIGHT = 600 +GRID_SIZE = 20 +GRID_WIDTH = WINDOW_WIDTH // GRID_SIZE +GRID_HEIGHT = WINDOW_HEIGHT // GRID_SIZE + +# Colors (RGB) +BLACK = (0, 0, 0) +WHITE = (255, 255, 255) +GREEN = (0, 255, 0) +RED = (255, 0, 0) +BLUE = (0, 0, 255) +YELLOW = (255, 255, 0) +PURPLE = (128, 0, 128) +ORANGE = (255, 165, 0) +GRAY = (128, 128, 128) +DARK_GREEN = (0, 150, 0) +LIGHT_GREEN = (144, 238, 144) + +# Game states +class GameState(Enum): + MENU = 1 + PLAYING = 2 + PAUSED = 3 + GAME_OVER = 4 + HIGH_SCORES = 5 + +# Directions +class Direction(Enum): + UP = (0, -1) + DOWN = (0, 1) + LEFT = (-1, 0) + RIGHT = (1, 0) + +class Snake: + def __init__(self, x, y): + self.body = [(x, y)] + self.direction = Direction.RIGHT + self.grow = False + + def move(self): + head_x, head_y = self.body[0] + dx, dy = self.direction.value + new_head = (head_x + dx, head_y + dy) + + self.body.insert(0, new_head) + + if not self.grow: + self.body.pop() + else: + self.grow = False + + def change_direction(self, new_direction): + # Prevent reversing into itself + if (self.direction == Direction.UP and new_direction == Direction.DOWN) or \ + (self.direction == Direction.DOWN and new_direction == Direction.UP) or \ + (self.direction == Direction.LEFT and new_direction == Direction.RIGHT) or \ + (self.direction == Direction.RIGHT and new_direction == Direction.LEFT): + return + self.direction = new_direction + + def grow_snake(self): + self.grow = True + + def check_collision(self): + head_x, head_y = self.body[0] + + # Check wall collision + if head_x < 0 or head_x >= GRID_WIDTH or head_y < 0 or head_y >= GRID_HEIGHT: + return True + + # Check self collision + if (head_x, head_y) in self.body[1:]: + return True + + return False + + def draw(self, screen): + for i, (x, y) in enumerate(self.body): + rect = pygame.Rect(x * GRID_SIZE, y * GRID_SIZE, GRID_SIZE, GRID_SIZE) + + if i == 0: # Head + pygame.draw.rect(screen, DARK_GREEN, rect) + pygame.draw.rect(screen, WHITE, rect, 2) + else: # Body + pygame.draw.rect(screen, GREEN, rect) + pygame.draw.rect(screen, WHITE, rect, 1) + +class Food: + def __init__(self): + self.position = self.generate_position() + self.type = random.choice(['normal', 'bonus', 'special']) + self.color = self.get_color() + + def generate_position(self): + x = random.randint(0, GRID_WIDTH - 1) + y = random.randint(0, GRID_HEIGHT - 1) + return (x, y) + + def get_color(self): + colors = { + 'normal': RED, + 'bonus': YELLOW, + 'special': PURPLE + } + return colors[self.type] + + def draw(self, screen): + x, y = self.position + rect = pygame.Rect(x * GRID_SIZE, y * GRID_SIZE, GRID_SIZE, GRID_SIZE) + pygame.draw.rect(screen, self.color, rect) + pygame.draw.rect(screen, WHITE, rect, 2) + + # Add special effects for different food types + if self.type == 'bonus': + inner_rect = pygame.Rect(x * GRID_SIZE + 4, y * GRID_SIZE + 4, + GRID_SIZE - 8, GRID_SIZE - 8) + pygame.draw.rect(screen, ORANGE, inner_rect) + elif self.type == 'special': + center_x = x * GRID_SIZE + GRID_SIZE // 2 + center_y = y * GRID_SIZE + GRID_SIZE // 2 + pygame.draw.circle(screen, WHITE, (center_x, center_y), 4) + +class Game: + def __init__(self): + self.screen = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT)) + pygame.display.set_caption("Snake Game - Classic Arcade") + self.clock = pygame.time.Clock() + self.font = pygame.font.Font(None, 36) + self.small_font = pygame.font.Font(None, 24) + self.large_font = pygame.font.Font(None, 72) + + self.state = GameState.MENU + self.score = 0 + self.high_score = self.load_high_score() + self.level = 1 + self.speed = 10 + self.snake = None + self.food = None + self.paused = False + + # Game settings + self.difficulty = "Medium" + self.sound_enabled = True + + def load_high_score(self): + try: + with open('high_score.json', 'r') as f: + data = json.load(f) + return data.get('high_score', 0) + except FileNotFoundError: + return 0 + + def save_high_score(self): + data = {'high_score': self.high_score} + with open('high_score.json', 'w') as f: + json.dump(data, f) + + def start_game(self): + self.state = GameState.PLAYING + self.score = 0 + self.level = 1 + self.speed = 10 + + # Initialize snake in center + start_x = GRID_WIDTH // 2 + start_y = GRID_HEIGHT // 2 + self.snake = Snake(start_x, start_y) + + # Generate first food + self.food = Food() + + # Adjust speed based on difficulty + if self.difficulty == "Easy": + self.speed = 8 + elif self.difficulty == "Hard": + self.speed = 15 + else: # Medium + self.speed = 10 + + def handle_events(self): + for event in pygame.event.get(): + if event.type == pygame.QUIT: + return False + + if event.type == pygame.KEYDOWN: + if self.state == GameState.MENU: + self.handle_menu_input(event.key) + elif self.state == GameState.PLAYING: + self.handle_game_input(event.key) + elif self.state == GameState.PAUSED: + self.handle_pause_input(event.key) + elif self.state == GameState.GAME_OVER: + self.handle_game_over_input(event.key) + elif self.state == GameState.HIGH_SCORES: + self.handle_high_scores_input(event.key) + + return True + + def handle_menu_input(self, key): + if key == pygame.K_1: + self.difficulty = "Easy" + self.start_game() + elif key == pygame.K_2: + self.difficulty = "Medium" + self.start_game() + elif key == pygame.K_3: + self.difficulty = "Hard" + self.start_game() + elif key == pygame.K_h: + self.state = GameState.HIGH_SCORES + elif key == pygame.K_ESCAPE: + return False + + def handle_game_input(self, key): + if key == pygame.K_UP or key == pygame.K_w: + self.snake.change_direction(Direction.UP) + elif key == pygame.K_DOWN or key == pygame.K_s: + self.snake.change_direction(Direction.DOWN) + elif key == pygame.K_LEFT or key == pygame.K_a: + self.snake.change_direction(Direction.LEFT) + elif key == pygame.K_RIGHT or key == pygame.K_d: + self.snake.change_direction(Direction.RIGHT) + elif key == pygame.K_SPACE: + self.state = GameState.PAUSED + elif key == pygame.K_ESCAPE: + self.state = GameState.MENU + + def handle_pause_input(self, key): + if key == pygame.K_SPACE: + self.state = GameState.PLAYING + elif key == pygame.K_ESCAPE: + self.state = GameState.MENU + + def handle_game_over_input(self, key): + if key == pygame.K_r: + self.start_game() + elif key == pygame.K_m: + self.state = GameState.MENU + elif key == pygame.K_ESCAPE: + return False + + def handle_high_scores_input(self, key): + if key == pygame.K_ESCAPE or key == pygame.K_m: + self.state = GameState.MENU + + def update_game(self): + if self.state != GameState.PLAYING: + return + + self.snake.move() + + # Check collision + if self.snake.check_collision(): + self.game_over() + return + + # Check food collision + if self.snake.body[0] == self.food.position: + self.eat_food() + + # Level up based on score + new_level = (self.score // 50) + 1 + if new_level > self.level: + self.level = new_level + self.speed = min(20, self.speed + 1) # Increase speed, max 20 + + def eat_food(self): + # Add score based on food type + if self.food.type == 'normal': + self.score += 10 + elif self.food.type == 'bonus': + self.score += 25 + elif self.food.type == 'special': + self.score += 50 + + self.snake.grow_snake() + + # Generate new food + self.food = Food() + + # Make sure food doesn't spawn on snake + while self.food.position in self.snake.body: + self.food = Food() + + # Update high score + if self.score > self.high_score: + self.high_score = self.score + self.save_high_score() + + def game_over(self): + self.state = GameState.GAME_OVER + + def draw_menu(self): + self.screen.fill(BLACK) + + # Title + title_text = self.large_font.render("SNAKE GAME", True, GREEN) + title_rect = title_text.get_rect(center=(WINDOW_WIDTH//2, 100)) + self.screen.blit(title_text, title_rect) + + # Subtitle + subtitle_text = self.font.render("Classic Arcade Experience", True, WHITE) + subtitle_rect = subtitle_text.get_rect(center=(WINDOW_WIDTH//2, 150)) + self.screen.blit(subtitle_text, subtitle_rect) + + # Menu options + menu_options = [ + "1. Easy Mode", + "2. Medium Mode (Default)", + "3. Hard Mode", + "H. High Scores", + "ESC. Exit" + ] + + y_offset = 250 + for option in menu_options: + text = self.font.render(option, True, WHITE) + text_rect = text.get_rect(center=(WINDOW_WIDTH//2, y_offset)) + self.screen.blit(text, text_rect) + y_offset += 50 + + # Instructions + instructions = [ + "Controls:", + "Arrow Keys or WASD - Move", + "Space - Pause", + "ESC - Menu/Exit" + ] + + y_offset = 500 + for instruction in instructions: + text = self.small_font.render(instruction, True, GRAY) + text_rect = text.get_rect(center=(WINDOW_WIDTH//2, y_offset)) + self.screen.blit(text, text_rect) + y_offset += 25 + + def draw_game(self): + self.screen.fill(BLACK) + + # Draw snake and food + self.snake.draw(self.screen) + self.food.draw(self.screen) + + # Draw UI + score_text = self.font.render(f"Score: {self.score}", True, WHITE) + self.screen.blit(score_text, (10, 10)) + + high_score_text = self.font.render(f"High Score: {self.high_score}", True, WHITE) + self.screen.blit(high_score_text, (10, 50)) + + level_text = self.font.render(f"Level: {self.level}", True, WHITE) + self.screen.blit(level_text, (10, 90)) + + # Pause indicator + if self.state == GameState.PAUSED: + pause_text = self.large_font.render("PAUSED", True, YELLOW) + pause_rect = pause_text.get_rect(center=(WINDOW_WIDTH//2, WINDOW_HEIGHT//2)) + self.screen.blit(pause_text, pause_rect) + + resume_text = self.font.render("Press SPACE to resume", True, WHITE) + resume_rect = resume_text.get_rect(center=(WINDOW_WIDTH//2, WINDOW_HEIGHT//2 + 50)) + self.screen.blit(resume_text, resume_rect) + + def draw_game_over(self): + self.screen.fill(BLACK) + + # Game Over text + game_over_text = self.large_font.render("GAME OVER", True, RED) + game_over_rect = game_over_text.get_rect(center=(WINDOW_WIDTH//2, 200)) + self.screen.blit(game_over_text, game_over_rect) + + # Final score + final_score_text = self.font.render(f"Final Score: {self.score}", True, WHITE) + final_score_rect = final_score_text.get_rect(center=(WINDOW_WIDTH//2, 280)) + self.screen.blit(final_score_text, final_score_rect) + + # High score + if self.score == self.high_score: + new_record_text = self.font.render("NEW HIGH SCORE!", True, YELLOW) + new_record_rect = new_record_text.get_rect(center=(WINDOW_WIDTH//2, 320)) + self.screen.blit(new_record_text, new_record_rect) + + # Options + options = [ + "R. Play Again", + "M. Main Menu", + "ESC. Exit" + ] + + y_offset = 400 + for option in options: + text = self.font.render(option, True, WHITE) + text_rect = text.get_rect(center=(WINDOW_WIDTH//2, y_offset)) + self.screen.blit(text, text_rect) + y_offset += 50 + + def draw_high_scores(self): + self.screen.fill(BLACK) + + # Title + title_text = self.large_font.render("HIGH SCORES", True, GREEN) + title_rect = title_text.get_rect(center=(WINDOW_WIDTH//2, 100)) + self.screen.blit(title_text, title_rect) + + # High score + high_score_text = self.font.render(f"Best Score: {self.high_score}", True, YELLOW) + high_score_rect = high_score_text.get_rect(center=(WINDOW_WIDTH//2, 200)) + self.screen.blit(high_score_text, high_score_rect) + + # Instructions + instruction_text = self.font.render("Press ESC or M to return to menu", True, WHITE) + instruction_rect = instruction_text.get_rect(center=(WINDOW_WIDTH//2, 300)) + self.screen.blit(instruction_text, instruction_rect) + + def draw(self): + if self.state == GameState.MENU: + self.draw_menu() + elif self.state == GameState.PLAYING or self.state == GameState.PAUSED: + self.draw_game() + elif self.state == GameState.GAME_OVER: + self.draw_game_over() + elif self.state == GameState.HIGH_SCORES: + self.draw_high_scores() + + pygame.display.flip() + + def run(self): + running = True + + while running: + running = self.handle_events() + + if self.state == GameState.PLAYING: + self.update_game() + + self.draw() + self.clock.tick(self.speed) + + pygame.quit() + sys.exit() + +def main(): + """Main function to run the Snake Game""" + print("šŸ Starting Snake Game...") + print("Controls:") + print(" Arrow Keys or WASD - Move") + print(" Space - Pause") + print(" ESC - Menu/Exit") + print(" R - Restart (Game Over)") + print(" H - High Scores") + print("\nEnjoy the game!") + + game = Game() + game.run() + +if __name__ == "__main__": + main() diff --git a/javascript/findMin.js b/javascript/findMin.js new file mode 100644 index 00000000..5f1c163e --- /dev/null +++ b/javascript/findMin.js @@ -0,0 +1,22 @@ +/** + * Finds the minimum value in an array of numbers. + * @param {number[]} arr - The array to search. + * @returns {number} The minimum value. + */ +function findMin(arr) { + if (!Array.isArray(arr) || arr.length === 0) { + throw new Error('Input must be a non-empty array'); + } + let min = arr[0]; + for (let i = 1; i < arr.length; i++) { + if (arr[i] < min) { + min = arr[i]; + } + } + return min; +} + +// Example usage: +// console.log(findMin([3, 1, 4, 1, 5, 9])); // Output: 1 + +module.exports = findMin; \ No newline at end of file diff --git a/pandas/Average Salary of Each Department.py b/pandas/Average Salary of Each Department.py new file mode 100644 index 00000000..ac282d5d --- /dev/null +++ b/pandas/Average Salary of Each Department.py @@ -0,0 +1,14 @@ +Employee = pd.DataFrame({ + 'id': [1, 2, 3, 4], + 'name': ['Alice', 'Bob', 'Charlie', 'David'], + 'salary': [5000, 7000, 6000, 8000], + 'departmentId': [1, 1, 2, 2] +}) +Department = pd.DataFrame({ + 'id': [1, 2], + 'name': ['HR', 'Engineering'] +}) + +merged = Employee.merge(Department, left_on='departmentId', right_on='id') +result = merged.groupby('name_y', as_index=False)['salary'].mean().rename(columns={'name_y': 'department'}) +print(result) diff --git a/pandas/Customers Who Never Ordered.py b/pandas/Customers Who Never Ordered.py new file mode 100644 index 00000000..89152990 --- /dev/null +++ b/pandas/Customers Who Never Ordered.py @@ -0,0 +1,12 @@ +Customers = pd.DataFrame({ + 'id': [1, 2, 3], + 'name': ['Alice', 'Bob', 'Charlie'] +}) +Orders = pd.DataFrame({ + 'id': [1, 2], + 'customerId': [1, 2] +}) + +merged = Customers.merge(Orders, left_on='id', right_on='customerId', how='left') +result = merged[merged['customerId'].isna()][['name']] +print(result) diff --git a/pandas/Department Highest Salary.py b/pandas/Department Highest Salary.py new file mode 100644 index 00000000..56c1b8c2 --- /dev/null +++ b/pandas/Department Highest Salary.py @@ -0,0 +1,16 @@ +Employee = pd.DataFrame({ + 'id': [1, 2, 3, 4], + 'name': ['Alice', 'Bob', 'Charlie', 'David'], + 'salary': [5000, 7000, 6000, 7000], + 'departmentId': [1, 1, 2, 2] +}) + +Department = pd.DataFrame({ + 'id': [1, 2], + 'name': ['HR', 'Engineering'] +}) + +merged = Employee.merge(Department, left_on='departmentId', right_on='id', suffixes=('', '_dept')) +max_salary = merged.groupby('departmentId')['salary'].transform('max') +result = merged[merged['salary'] == max_salary][['name_dept', 'name', 'salary']] +print(result) diff --git a/pandas/Employees Earning More Than Their Managers.py b/pandas/Employees Earning More Than Their Managers.py new file mode 100644 index 00000000..fcc173cb --- /dev/null +++ b/pandas/Employees Earning More Than Their Managers.py @@ -0,0 +1,13 @@ +import pandas as pd + +data = { + 'id': [1, 2, 3, 4], + 'name': ['Alice', 'Bob', 'Charlie', 'David'], + 'salary': [5000, 7000, 6000, 8000], + 'managerId': [None, 1, 1, 2] +} +Employee = pd.DataFrame(data) + +df = Employee.merge(Employee, left_on='managerId', right_on='id', suffixes=('', '_manager')) +result = df[df['salary'] > df['salary_manager']][['name']] +print(result) diff --git a/pandas/Second Highest Salary.py b/pandas/Second Highest Salary.py new file mode 100644 index 00000000..037febac --- /dev/null +++ b/pandas/Second Highest Salary.py @@ -0,0 +1,6 @@ +Employee = pd.DataFrame({ + 'id': [1, 2, 3], + 'salary': [100, 200, 300] +}) +second_highest = Employee['salary'].drop_duplicates().nlargest(2).min() +print(second_highest)