🧠 Python Feature That Makes Type Checking Smarter: typing.Protocol Duck typing… but official 🦆✨ 🤔 The Problem 💻 Python is dynamically typed. 💻 But sometimes you want structure without inheritance. ❌ Traditional Way class Bird: def fly(self): ... def start_flying(bird: Bird): bird.fly() This forces inheritance. ✅ Pythonic Way with Protocol from typing import Protocol class Flyable(Protocol): def fly(self) -> None: ... def start_flying(obj: Flyable): obj.fly() 💫 Now ANY object with fly() works. 💫 No inheritance required 🎯 🧒 Simple Explanation 🦆 If it quacks like a duck and walks like a duck… 🦆 it doesn’t need to be a Duck class. 🦆 That’s Protocol. 💡 Why This Is Powerful ✔ Structural typing ✔ Cleaner architecture ✔ Better static analysis ✔ Used heavily in modern Python frameworks ⚡ Real Example class Drone: def fly(self): print("Flying") start_flying(Drone()) # Works! 🐍 Python believes in behavior, not hierarchy 🐍 typing.Protocol makes duck typing formal and powerful. #Python #PythonTips #PythonTricks #AdvancedPython #CleanCode #LearnPython #Programming #DeveloperLife #DailyCoding #100DaysOfCode
Python Protocol for Duck Typing
More Relevant Posts
-
🚀 Day 2 – DSA Series Remove Duplicates from Sorted Array Solved LeetCode 26 – Remove Duplicates from Sorted Array using Python. 🧠 Problem Summary Given a sorted array nums, remove duplicates in-place such that each unique element appears only once. Return the number of unique elements k, where: • The first k elements of nums contain the unique values • The remaining elements beyond k don’t matter • No extra array allowed (O(1) space) Example: Input: [1, 1, 2] Output: k = 2 → Modified array: [1, 2, _] 💡 Approach Used (Two Pointer Technique) Since the array is sorted, duplicates are adjacent. ✔️ Initialized k = 1 (first element always unique) ✔️ Iterated from index 1 ✔️ Compared current element with previous element ✔️ When a new unique element is found: • Placed it at index k • Incremented k This ensures in-place modification without extra space. ⏱ Complexity Analysis Time Complexity: O(n) – single pass Space Complexity: O(1) – no additional data structures 🔎 Key Takeaway This problem strengthens: • Two Pointer pattern • In-place array manipulation • Understanding problem constraints carefully Continuing the DSA series — one problem at a time. 🚀 #DSA #LeetCode #Python #Algorithms #TwoPointers #ProblemSolving #CodingJourney
To view or add a comment, sign in
-
-
🧠 Python Concept: List Comprehension Write powerful loops in one clean line. ❌ Traditional Way squares = [] for i in range(5): squares.append(i * i) print(squares) Output [0, 1, 4, 9, 16] ✅ Pythonic Way squares = [i * i for i in range(5)] print(squares) Same result, less code. ⚡ With Condition even_squares = [i * i for i in range(10) if i % 2 == 0] print(even_squares) Output [0, 4, 16, 36, 64] 🧒 Simple Explanation Imagine telling a robot: 👉 “Give me squares of numbers from 0–4.” 👉 Instead of repeating instructions, you give one rule. 👉 That rule = list comprehension. 💡 Why This Matters ✔ Shorter code ✔ Faster execution ✔ More readable loops ✔ Very Pythonic 🐍 Python often replaces multiple lines with a single elegant expression 🐍 List comprehensions are one of the most powerful examples of that philosophy. #Python #PythonTips #PythonTricks #AdvancedPython #List #ListComprehension #Tech #CleanCode #LearnPython #Programming #DeveloperLife #DailyCoding #100DaysOfCode
To view or add a comment, sign in
-
-
If you are interested in acoustic radiance transfer (ART) and/or its modal decomposition (MoD-ART), you'll be happy to know that a Python implementation is available on GitHub at the link below! The repository includes notes about the underlying theory, examples of files describing environments to be analyzed, and example scripts demonstrating how to use the package. A Jupyter notebook walks through a basic use case. I hope you'll find these tools useful in your research! https://lnkd.in/efiDU393
To view or add a comment, sign in
-
#Projects 🚀 Excited to share my latest project: Thread Shed 🧵✨ https://lnkd.in/gssBsFwy Working with complex string data in Python has always fascinated me. This project was born out of the challenge of handling messy, layered text structures and turning them into something clean, efficient, and insightful. 🔹 Why it matters: Speeds up data parsing and transformation Handles intricate string manipulations with clarity Demonstrates how concurrency can simplify real-world text-heavy workflows 👉 I’d love to hear how others approach complex string challenges in Python. Do you lean on regex, threading, or something else entirely? #Python #Threading #StringProcessing #DataEngineering #Innovation Would you like me to make this post more technical (with code snippets and performance metrics) or more story-driven (focusing on your personal journey and motivation)?
To view or add a comment, sign in
-
-
🧠 Python Concept: sorted() vs sort() ✨ Both sort data, but they behave differently. ✨ sorted() → Returns a new sorted list numbers = [5, 2, 8, 1] result = sorted(numbers) print(numbers) # Original list print(result) # Sorted list Output [5, 2, 8, 1] [1, 2, 5, 8] The original list stays unchanged. ✨ list.sort() → Sorts in place numbers = [5, 2, 8, 1] numbers.sort() print(numbers) Output [1, 2, 5, 8] The original list is modified. 🧒 Simple Explanation 📚 Imagine arranging books 📚 sorted() → makes a new sorted pile 📚 sort() → rearranges the same pile 💡 Why This Matters ✔ Understand side effects ✔ Avoid unexpected bugs ✔ Cleaner data processing ✔ Common interview question 🐍 In Python, sorted() and sort() look similar but behave differently 🐍 One creates a new list, the other modifies the existing one. #Python #PythonTips #PythonTricks #AdvancedPython #CleanCode #LearnPython #Programming #DeveloperLife #DailyCoding #100DaysOfCode
To view or add a comment, sign in
-
-
LeetCode #15 – 3Sum | Python Implementation I implemented a sort-based two-pointer approach to find all unique triplets that sum to zero. Sorting the array upfront enables two key optimizations: duplicate skipping and directional pointer movement. For each element n as the fixed anchor, two pointers l and r converge inward adjusting based on whether the current sum is too small or too large. Duplicate anchors are skipped at the outer loop level, and after finding a valid triplet, the left pointer advances past any duplicates to ensure uniqueness. This pattern is foundational in computational geometry, collision detection systems, and financial portfolio balancing algorithms. Key Takeaway: Sorting transforms an O(n³) brute-force problem into O(n²) by enabling the two-pointer convergence strategy. The duplicate-skipping logic at both the anchor and left-pointer level is what guarantees unique triplets without using extra space like a HashSet. Time: O(n²) | Space: O(1) or O(n) (excluding output array) #LeetCode #DataStructures #Python #TwoPointers #Sorting #CodingInterview #ProblemSolving #SoftwareEngineering
To view or add a comment, sign in
-
-
🚀 Day 44 of #100DaysOfCode 📌 Problem: 762 – Prime Number of Set Bits in Binary Representation Today I solved an interesting bit manipulation problem on LeetCode that combines binary representation with prime number logic. 🔎 Problem Summary: Given two integers left and right, count how many numbers in that range have a prime number of set bits (1s) in their binary form. 💡 Key Insight: The maximum number of set bits for numbers ≤ 10⁶ is 20. So we only need to check prime numbers up to 20: {2, 3, 5, 7, 11, 13, 17, 19} For each number, count the set bits using: Python Copy code num.bit_count() ✅ Python Solution: Python Copy code class Solution: def countPrimeSetBits(self, left: int, right: int) -> int: primes = {2, 3, 5, 7, 11, 13, 17, 19} count = 0 for num in range(left, right + 1): if num.bit_count() in primes: count += 1 return count ⏱ Time Complexity: O(n) 🧠 Concepts Used: Bit Manipulation | Prime Numbers | Set Every day I’m getting more comfortable with binary operations and optimization techniques. #LeetCode #Day42 #CodingJourney #Python #ProblemSolving #BitManipulation #100DaysOfCode
To view or add a comment, sign in
-
-
If you've been putting off adding AI image generation to your Python stack — this is your sign. 🐍 New tutorial just published: How to Use the Stable Diffusion API with Python What you'll learn: → API authentication and setup → Generating images from text prompts → Controlling model parameters for better outputs → Production-ready code you can deploy today Stable Diffusion API integration doesn't need to be complicated. With ModelsLab's API, you're generating images in under 5 minutes — no GPU required. Full tutorial → https://lnkd.in/gSDKdZ_5 Whether you're building a creative app, automating design workflows, or just exploring generative AI — this is the foundation. Questions? Drop them in the comments 👇 #StableDiffusion #Python #GenerativeAI #API #DeveloperTutorial #MachineLearning #AIImageGeneration
To view or add a comment, sign in
-
LeetCode Problem 1143: "Longest Common Subsequence": Given two strings text1 and text2, return the length of their longest common subsequence. If there is no common subsequence, return 0. A subsequence of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters. For example, "ace" is a subsequence of "abcde". A common subsequence of two strings is a subsequence that is common to both strings. The below implementation in Python resolves this problem in O(m*n) time and space complexity using the dynamic programming approach. A dp array is created whose cells store the value of longest common subsequence upto a specific length of text1 and text2. At the last cell we get the value of "longest common subsequence" for the given two strings. #Python #LeetCode #DynamicProgramming #Algorithms #DataStructures #CompetitiveProgramming #CodingChallenge #ProblemSolving
To view or add a comment, sign in
-
-
🚀 Day 1 – DSA Series Two Sum (LeetCode) Starting my DSA problem-solving series with the classic Two Sum problem, implemented in Python. 🧠 Problem Statement Given an integer array nums and an integer target, return the indices of the two numbers such that they add up to the target. Constraints: • Exactly one valid solution exists. • The same element cannot be used twice. • The answer can be returned in any order. Example: nums = [2, 7, 11, 15], target = 9 Output: [0, 1] Because 2 + 7 = 9. 💡 Approach Implemented I used the nested loop (brute force) approach: • Iterate through each element • Check all remaining elements • Return indices when sum equals target ⏱ Complexity Analysis Time Complexity: O(n²) Space Complexity: O(1) Even for a well-known problem, breaking it down step by step helps strengthen logical thinking and reinforces core fundamentals before jumping to optimized solutions. I’ll be solving and sharing one DSA problem daily -focusing on clarity, approach, and complexity analysis. Let’s build consistency. 🚀 #DSA #LeetCode #Python #Algorithms #ProblemSolving #SoftwareEngineering #CodingJourney
To view or add a comment, sign in
-
Explore related topics
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