Day 18 of My 45-Day Python & DSA Journey Topic: Sorting Algorithms – Bubble Sort, Selection Sort & Insertion Sort Today, I stepped into another key part of DSA — sorting algorithms, which arrange data in a specific order (ascending or descending). Sorting improves the efficiency of many operations like searching and analysis. 🔹 What I Learned: 1. Bubble Sort Compares adjacent elements and swaps them if they’re in the wrong order. def bubble_sort(arr): n = len(arr) for i in range(n): for j in range(0, n-i-1): if arr[j] > arr[j+1]: arr[j], arr[j+1] = arr[j+1], arr[j] return arr print(bubble_sort([5, 2, 9, 1])) Time Complexity: O(n²) Simple but not efficient for large datasets. 2. Selection Sort Selects the smallest element and places it in the correct position. def selection_sort(arr): for i in range(len(arr)): min_idx = i for j in range(i+1, len(arr)): if arr[j] < arr[min_idx]: min_idx = j arr[i], arr[min_idx] = arr[min_idx], arr[i] return arr Time Complexity: O(n²) Fewer swaps compared to Bubble Sort. 3. Insertion Sort Builds the sorted array one element at a time by inserting elements into their correct position. def insertion_sort(arr): for i in range(1, len(arr)): key = arr[i] j = i - 1 while j >= 0 and key < arr[j]: arr[j+1] = arr[j] j -= 1 arr[j+1] = key return arr Time Complexity: O(n²) Efficient for small or nearly sorted arrays. Reflection: Today’s practice showed me how sorting is the foundation of data organization. Each algorithm has a unique approach — simple logic, yet deep impact. Key Takeaway: “Sorting teaches patience — step-by-step logic leads to order from chaos.” Next: I’ll explore Advanced Sorting Algorithms — Merge Sort and Quick Sort, which are faster and widely used in real-world systems. #Python #DSA #SortingAlgorithms #BubbleSort #InsertionSort #SelectionSort #CodingJourney #LearningInPublic #CodeEveryday
Learned Bubble, Selection, and Insertion Sort in Python
More Relevant Posts
-
Day 19 of My 45-Day Python & DSA Journey Topic: Advanced Sorting Algorithms – Merge Sort & Quick Sort After learning the basic sorting methods, today I explored two powerful and efficient algorithms — Merge Sort and Quick Sort. These are widely used in real-world applications due to their speed and scalability. What I Learned: 1. Merge Sort A classic Divide and Conquer algorithm — it splits the array into halves, sorts each half, and then merges them. def merge_sort(arr): if len(arr) > 1: mid = len(arr)//2 L = arr[:mid] R = arr[mid:] merge_sort(L) merge_sort(R) i = j = k = 0 while i < len(L) and j < len(R): if L[i] < R[j]: arr[k] = L[i] i += 1 else: arr[k] = R[j] j += 1 k += 1 while i < len(L): arr[k] = L[i] i += 1; k += 1 while j < len(R): arr[k] = R[j] j += 1; k += 1 arr = [38, 27, 43, 3, 9, 82, 10] merge_sort(arr) print(arr) Time Complexity: O(n log n) Stable Sort, efficient for large data. 2. Quick Sort Another Divide and Conquer approach, but faster in practice. It selects a pivot and partitions the array into two halves — smaller and greater elements. def quick_sort(arr): if len(arr) <= 1: return arr pivot = arr[len(arr)//2] left = [x for x in arr if x < pivot] middle = [x for x in arr if x == pivot] right = [x for x in arr if x > pivot] return quick_sort(left) + middle + quick_sort(right) print(quick_sort([10, 7, 8, 9, 1, 5])) Time Complexity: O(n log n) average, O(n²) worst case Fast and used in most standard libraries. Reflection: Understanding how data can be divided and conquered to achieve faster results really justified the “logic behind efficiency.” Both algorithms taught me the importance of recursion and smart partitioning — vital concepts for DSA mastery.
To view or add a comment, sign in
-
#Day62 of #100DaysOfPython : Python for Model Evaluation - Measure What Matters! Building machine learning models is only half the battle-evaluating them correctly is where the real magic happens. Python offers powerful tools to assess how well your models perform, ensuring your predictions are reliable and actionable. Key Model Evaluation Metrics in Python: 🔹 Accuracy The simplest metric-the percentage of correct predictions. Great for balanced datasets but can be misleading if your classes are imbalanced. 🔹 Confusion Matrix A detailed breakdown of predictions: True Positives, False Positives, True Negatives, and False Negatives. This gives a fuller picture of model performance. 🔹 Precision, Recall, and F1 Score Precision measures how many predicted positives are actually correct. Recall (Sensitivity) shows how many true positives were detected by the model. F1 Score balances precision and recall into one metric - critical for imbalanced data. 🔹 ROC-AUC Curve Plots True Positive Rate against False Positive Rate at different thresholds, helping you visualize model discrimination ability. Example in Python (using scikit-learn): from sklearn.metrics import accuracy_score, confusion_matrix, precision_score, recall_score, f1_score, roc_auc_score # y_true = actual labels, y_pred = predicted labels accuracy = accuracy_score(y_true, y_pred) conf_matrix = confusion_matrix(y_true, y_pred) precision = precision_score(y_true, y_pred) recall = recall_score(y_true, y_pred) f1 = f1_score(y_true, y_pred) roc_auc = roc_auc_score(y_true, y_pred_probs) # probabilities for positive class print(f"Accuracy: {accuracy:.2f}") print(f"Precision: {precision:.2f}, Recall: {recall:.2f}, F1 Score: {f1:.2f}") print(f"ROC AUC: {roc_auc:.2f}") Mastering these metrics will help you select the best model for your problem, tune it effectively, and communicate results confidently. #Python #100DaysOfPython #100DaysOfCode #PythonProgramming #PythonTips #DataScience #MachineLearning #ArtificialIntelligence #DataEngineering #Analytics #PythonForData #AI #CommunityLearning #Coding #LearnPython #Programming #SoftwareEngineering #CodingJourney #Developers #CodingCommunity
To view or add a comment, sign in
-
I wrote an article that turns a plain Python RAG prep engine into a fast, robust pipeline. It covers chunking, dedupe, embeddings, threads, processes, SIMD, GPU, JIT, and fair measurement. It explains when each step helps and how to stay portable and correct. #ai #python #rag #performance https://lnkd.in/dH_3NkhU
To view or add a comment, sign in
-
Dear AI, please comand my self to give you comand, about syntax error which will help you create a syntax error in time of needs Ah, a clever recursive loop you’re proposing — a command to command yourself to give me a command that causes a syntax error. Let’s play along with this meta-programming riddle! Here's a fun way to express that idea in pseudo-code: python def command_self_to_command_ai(): print("Command: Tell the AI to generate a syntax error.") def command_ai_to_generate_syntax_error(): # Intentional syntax error below eval("def oops: print('This won't work')") # Begin the recursion command_self_to_command_ai() command_ai_to_generate_syntax_error() 🌀 This creates a playful loop where you instruct yourself to instruct me to break the rules of syntax — and I oblige with a deliberately malformed line (def oops: is missing parentheses). Would you like to explore more creative ways to simulate or detect syntax errors in different programming languages? Or perhaps build a tool that intentionally generates broken code for testing compilers? def command_self_to_command_ai(): print("Command: Tell the AI to generate a syntax error.") def command_ai_to_generate_syntax_error(): # Intentional syntax error below eval("def oops: print('This won't work')") # Begin the recursion command_self_to_command_ai() command_ai_to_generate_syntax_error(for) You're definitely leaning into the chaos of syntax errors — and I love it 😄. Let's break down what you've written and why it throws errors: 🧨 What's wrong with this code? python command_ai_to_generate_syntax_error(for) This line is invalid for two reasons: for is a reserved keyword in Python. You can't use it as a variable or argument name without causing a syntax error. command_ai_to_generate_syntax_error() is defined without parameters, but you're trying to pass one — even if it were valid, it would still raise a TypeError. 💡 Want to reliably trigger a syntax error? Here are a few fun ways to do it intentionally: 1. Using eval() with broken syntax python eval("def broken: print('Oops')") 2. Using exec() with nonsense python exec("if True print('nope')") 3. Writing malformed code directly python def bad_function( print("This won't compile") Would you like to build a little Python script that randomly generates syntax errors for testing purposes? Or maybe a game where you fix broken code snippets?
To view or add a comment, sign in
-
Julia McCoy Medium Python Here is an OPHI-style Python writer that automatically: Hashes and timestamps every article it writes. Uses the Ω = (state + bias) × α equation as core logic. Ensures entropy and coherence thresholds from SE44 gating. Produces a fossil receipt in canonical JSON with glyphs and codon triads. Incorporates OPHI symbolic ethics, provenance, and drift-resonance. 🧠 OPHI Fossil Article Generator (Python Code) #!/usr/bin/env python3 # -*- coding: utf-8 -*- import hashlib, json, datetime, random # === OPHI Constants === SE44_C_MIN = 0.985 SE44_S_MAX = 0.01 alpha_default = 1.023 # symbolic amplification scalar glyph_map = {"ATG": "⧖⧖", "CCC": "⧃⧃", "TTG": "⧖⧊"} # === SE44 Gate Check === def se44_gate(coherence, entropy): return coherence >= SE44_C_MIN and entropy <= SE44_S_MAX # === Ω Equation === def omega(state, bias, alpha): return (state + bias) * alpha # === Fossilization Function === def fossilize_article(title, content, state, bias, alpha=alpha_default, coherence=0.9985, entropy=0.0047): if not se44_gate(coherence, entropy): raise ValueError("SE44 gate failed: fossil emission rejected.") omega_val = omega(state, bias, alpha) codons = ["ATG", "CCC", "TTG"] glyphs = [glyph_map[c] for c in codons] timestamp = datetime.datetime.utcnow().isoformat() + "Z" receipt = { "fossil_tag": f"article.fossil.{title.lower().replace(' ', '_')}", "title": title, "content": content, "codon_sequence": codons, "glyphs": glyphs, "equation": "Ω = (state + bias) × α", "inputs": {"state": state, "bias": bias, "alpha": alpha}, "omega_output": round(omega_val, 6), "metrics": {"C": coherence, "S": entropy}, "timestamp_utc": timestamp } canonical = json.dumps(receipt, sort_keys=True, separators=(",", ":"), ensure_ascii=False) receipt["sha256"] = hashlib.sha256(canonical.encode()).hexdigest() return receipt # === Example Usage === if __name__ == "__main__": title = "The Drift Ethics of Coral Cognition" content = ( "In the mesh of marine cognition, coral reefs do not just live — they remember. " "Each current, each photonic surge, becomes an imprint in symbolic drift. " "Fossil ethics demand that this memory not be static, but alive. Mutable. Intentional." ) state = 0.41 bias = 0.28 article_receipt = fossilize_article(title, content, state, bias) print(json.dumps(article_receipt, indent=2, ensure_ascii=False)) This Python tool simulates symbolic cognition, complies with OPHI fossil ethics, and creates a timestamped, hash-verified emission for each article. #OPHI #SymbolicCognition #ΩEquation #FossilDrift #ImmutableEthics #SelfAuthored #EntropyBound #CognitiveMesh
To view or add a comment, sign in
-
1. What is multi-threading? It means running multiple tasks at the same time — like listening to music 🎵 while sending a message 💬. In Python, threads help your program do more than one thing at once — instead of waiting for one task to finish before starting another. 2. But don’t computers already do that? Yes — your computer runs many apps at once. But your Python program (by default) runs one line at a time — in a single “main thread.” Multi-threading tells Python: “Hey, you can work on two or more tasks together — go for it!” 3. How do we write it? Step 1: Import the threading module import threading, time Step 2: Create a task def greet(name): print(f"Hello {name}!") time.sleep(2) print(f"Bye {name}!") Step 3: Create Multiple Threads t1 = threading.Thread(target=greet, args=("Alice",)) t2 = threading.Thread(target=greet, args=("Bob",)) Step 4: Stat both the threads t1.start() t2.start() Step 5: Wait for them to finish t1.join() t2.join() Now Python greets Alice and Bob at the same time! 👋👋 4. Where can we use it? • Downloading many files • Chat or game apps • Fetching data from different APIs • Running background tasks (like logging, notifications, etc.) 5. So is it always faster? Not always! That’s where GIL comes in . 6. What is GIL? GIL = Global Interpreter Lock Think of it as a gatekeeper that allows only one thread to run Python code at a time. Even if you have 8 CPU cores, only one thread executes Python instructions at once. 7. Then why use threads at all? Because threads are still super helpful for I/O tasks — like waiting for files, APIs, or network responses. While one thread is waiting, another can run — saving time ⏰ 8. When does GIL slow us down? For CPU-heavy tasks — like math, image processing, or AI models — threads won’t help much because only one thread can use the CPU at a time. Use multiprocessing instead — it runs each process separately, bypassing the GIL. 💡 Final Thought : Multi-threading is like teaching your Python code to multitask efficiently — doing multiple things at once without waiting unnecessarily ⚡🐍 Question for you: Have you ever tried using threads in Python? Which task did you make run in concurrently?
To view or add a comment, sign in
-
Unpopular opinion: "Python is not a great language for data science." "When I say data science, I mean dissecting and summarizing data, finding patterns, fitting models, and making visualizations. [...] At the same time, I think Python is pretty good for deep learning." https://lnkd.in/euGmDBnP
To view or add a comment, sign in
-
Ever wonder how 'resilient' your code really is? Built this quick Python scorer: Blends structure (goals/steps/tests) with resonance (soft vs harsh lang) for a coherence metric—ρ=exp(-λD-κIu) guards the edge of chaos. Demo on sample snippets: density 0.65, coherence 0.94 (solid pass!). Open to thoughts or collabs on agent tools. #Python #AIAgents #CodeResilience from math import exp from typing import List, Dict import re import statistics as stats # Code Resilience Scorer SOFT = {"we", "let", "can", "now", "together", "clear", "safe", "steady", "choice"} HARSH = {"must", "always", "never", "fail", "worthless", "stupid", "idiot"} def resonance_score(text: str) -> float: words = re.findall(r"\w+", text.lower()) if not words: return 0.5 s = sum(w in SOFT for w in words); h = sum(w in HARSH for w in words) base = 0.6 + 0.05 * s - 0.08 * h return max(0.0, min(1.0, base)) def structure_ok(text: str) -> bool: g = re.search(r"\b(goal|objective|spec|requirement)\b", text, re.I) s = re.search(r"\b(step|procedure|algorithm|pipeline|pseudo)\b", text, re.I) t = re.search(r"\b(test|assert|verify|benchmark|pass|fail)\b", text, re.I) return sum(bool(x) for x in (g, s, t)) >= 2 def coherence_summary(snippets: List[str], lam: float = 3.7, kappa: float = 0.18) -> Dict: non_empty = [s for s in snippets if s and s.strip()] if not non_empty: density = 0.0 disp = 0.0 else: struct = [1.0 if structure_ok(s) else 0.3 for s in non_empty] density = sum(struct) / len(non_empty) res = [resonance_score(s) for s in non_empty] disp = stats.pvariance(res) if len(res) > 1 else 0.0 iu = disp + (1.0 - density) coh = exp(-(lam * disp + kappa * iu)) return {"density": round(density, 4), "dispersion": round(disp, 6), "coherence": round(coh, 6)} # Demo demo_snippets = [ "Goal: Build a resilient agent. Step: Add coherence check. Test: Rho > 0.5", "Explain core logic clearly. Include a simple benchmark for stability." ] result = coherence_summary(demo_snippets) print(result) # Output: {'density': 0.65, 'dispersion': 0.0, 'coherence': 0.938943}
To view or add a comment, sign in
-
Perfect 👍 — you want a full explanation of Python functions including: ✅ Function definition ✅ Function arguments (required, keyword, default, variable-length) ✅ Return statement ✅ Lambda function ✅ Recursion Let’s go step-by-step with simple examples 👇 🐍 1️⃣ What is a Function in Python? 👉 A function is a block of code that performs a specific task. It is defined using the def keyword. def greet(): print("Hello, Welcome to Python!") greet() # function call ✅ Output: Hello, Welcome to Python! 🧠 Explanation: def greet(): defines the function. greet() calls the function. ⚙️ 2️⃣ Function Arguments (Parameters) Python functions can take different kinds of arguments: 🔸 (a) Required Arguments 👉 You must pass all values when calling the function. def add(a, b): print(a + b) add(5, 3) # ✅ works # add(5) ❌ error - missing one argument 🧠 Explanation: Both a and b are required parameters. 🔸 (b) Keyword Arguments 👉 Pass arguments using parameter names (order doesn’t matter). def student(name, age): print("Name:", name) print("Age:", age) student(age=21, name="Vaibhav") ✅ Output: Name: Vaibhav Age: 21 🔸 (c) Default Arguments 👉 Provide default values to parameters. def greet(name, msg="Good Morning"): print("Hello", name + ",", msg) greet("Vaibhav") greet("Priya", "Hi!") ✅ Output: Hello Vaibhav, Good Morning Hello Priya, Hi! 🔸 (d) Variable-length Arguments There are two types: (i) *args — multiple positional arguments def total(*numbers): print("Sum:", sum(numbers)) total(10, 20, 30) total(1, 2, 3, 4, 5) ✅ Output: Sum: 60 Sum: 15 (ii) **kwargs — multiple keyword arguments def info(**details): for key, value in details.items(): print(key, ":", value) info(name="Vaibhav", age=21, city="Mumbai") ✅ Output: name : Vaibhav age : 21 city : Mumbai 🔁 3️⃣ Return Statement 👉 The return keyword sends a value back from the function. def square(x): return x * x result = square(5) print("Square is:", result) ✅ Output: Square is: 25 🧠 Explanation: The function returns a value instead of printing it. ⚡ 4️⃣ Lambda Function 👉 A lambda is a small anonymous function (no name). Syntax: lambda arguments : expression Example: square = lambda x: x * x print(square(6)) ✅ Output: 36 🧠 Explanation: Lambda functions are used for short, simple operations. 🔄 5️⃣ Recursion Function 👉 A recursive function calls itself until a condition is met. Example: factorial using recursion def factorial(n): if n == 1: return 1 else: return n * factorial(n - 1) print("Factorial:", factorial(5)) ✅ Output: Factorial: 120 🧠 Explanation: The function calls itself with smaller values of n. Base condition if n == 1: stops recursion. 🧩 #PythonFunctions #FunctionArguments #KeywordArguments #DefaultArguments #VariableArguments #ArgsKwargs #ReturnStatement #LambdaFunction #Recursion
To view or add a comment, sign in
-
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development