Can you code and show me 2-3 useful but small examples
- User
Can you code and show me 2-3 useful but small examples
Assistant
I'd be happy to show you some useful small code examples! Here are three practical snippets:
1. Password Strength Checker
import re def check_password_strength(password): """Check password strength and return score with feedback""" score = 0 feedback = [] # Length check if len(password) >= 8: score += 1 else: feedback.append("Use at least 8 characters") # Check for uppercase if re.search(r'[A-Z]', password): score += 1 else: feedback.append("Include uppercase letters") # Check for lowercase if re.search(r'[a-z]', password): score += 1 else: feedback.append("Include lowercase letters") # Check for numbers if re.search(r'\d', password): score += 1 else: feedback.append("Include numbers") # Check for special characters if re.search(r'[!@#$%^&*(),.?":{}|<>]', password): score += 1 else: feedback.append("Include special characters") strength = ["Very Weak", "Weak", "Fair", "Good", "Strong"][score] return { "score": score, "strength": strength, "feedback": feedback } # Example usage result = check_password_strength("MyPass123!") print(f"Strength: {result['strength']} ({result['score']}/5)")2. Simple To-Do List Manager
class TodoList { constructor() { this.todos = []; this.nextId = 1; } add(task) { const todo = { id: this.nextId++, task: task, completed: false, createdAt: new Date() }; this.todos.push(todo); return todo; } complete(id) { const todo = this.todos.find(t => t.id === id); if (todo) { todo.completed = true; todo.completedAt = new Date(); return true; } return false; } remove(id) { const index = this.todos.findIndex(t => t.id === id); if (index !== -1) { return this.todos.splice(index, 1)[0]; } return null; } getActive() { return this.todos.filter(t => !t.completed); } getCompleted() { return this.todos.filter(t => t.completed); } } // Example usage const myTodos = new TodoList(); myTodos.add("Buy groceries"); myTodos.add("Call dentist"); myTodos.add("Finish report"); myTodos.complete(1); console.log("Active tasks:", myTodos.getActive().map(t => t.task));3. Text File Word Counter
from collections import Counter import string def analyze_text_file(filename): """Analyze a text file and return word statistics""" try: with open(filename, 'r', encoding='utf-8') as file: text = file.read().lower() # Remove punctuation translator = str.maketrans('', '', string.punctuation) text = text.translate(translator) # Split into words words = text.split() # Calculate statistics word_count = len(words) unique_words = len(set(words)) word_freq = Counter(words) # Find average word length avg_length = sum(len(word) for word in words) / word_count if words else 0 return { "total_words": word_count, "unique_words": unique_words, "average_word_length": round(avg_length, 2), "most_common": word_freq.most_common(10), "longest_word": max(words, key=len) if words else None } except FileNotFoundError: return {"error": "File not found"} except Exception as e: return {"error": str(e)} # Example usage stats = analyze_text_file("document.txt") if "error" not in stats: print(f"Total words: {stats['total_words']}") print(f"Unique words: {stats['unique_words']}") print(f"Top 5 words: {stats['most_common'][:5]}")These examples demonstrate:
- Input validation and feedback (password checker)
- Object-oriented design with practical methods (todo list)
- File handling with error management (word counter)
Each is self-contained and can be easily adapted for different use cases. Would you like me to explain any specific part or show variations of these examples?
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.