🐍 Python Practice Progress ( 21 out of 50 question solved) Here are the problems I recently solved: ✅ Count even and odd numbers in a list ✅ Reverse a list without using reverse() ✅ Insert the third largest number at the second last position in a list. ✅ Find the sum of all elements in a list ✅ Merge two lists ✅ Find common elements between two lists ✅ Sort a list without using sort() Working through these exercises helped reinforce concepts like: • loops and indexing • list operations • conditional logic • problem-solving without relying on built-in shortcuts Sometimes going back to the basics is the best way to build stronger foundations. Day 3 ------------------- Count even and odd numbers in a list. try: Num1=[1,2,3,4,5,6,7,8,9,9,88] even=0 odd=0 for i in Num1: if i%2==0: even=even+1 elif i%2!=0: odd=odd+1 print("even are ",even) print("odd are ", odd) except ValueError: print("Some error occured.") Reverse a list without using reverse(). list1=[1,2,3,4,5,6,7] rev_list=[] rev_list=list1[::-1] print(rev_list) # or try: list1=[1,2,3,4,5,6,7] rev_list=[] for i in list1: rev_list.insert(0,i) print(rev_list) except ValueError: print("error occured.") or try: list1=[1,2,3,4,5,6,7] rev_list=[] for i in range(len(list1)-1,-1,-1): rev_list.append(list1[i]) print(rev_list) except ValueError: print("error occured.") Insert third largest number in a list and add it at second last position. try: list1=[1,2,76,84,989,23,4,5,666,7,788,8,9897] third_largest=sorted(list1)[-3] list1.insert(len(list1)-1,third_largest) print(list1) Find the sum of all elements in a list. try: list1=[2,4,5,4,44,33,65,898,90] s=0 for i in list1: s=s+i print(s) except ValueError: print("error occured") Merge two lists. try: list1=[2,3,4,4,5,6,7] list2=[99,8,0,4,2,1] c=list1+list2 print(c) except ValueError: print("error occured") using extend method try: list1=[2,3,4,4,5,6,7] list2=[99,8,0,4,2,1] list1.extend(list2) print(list1) except ValueError: print("error occured") # Find common elements between two lists. try: list1=[2,3,4,4,5,6,7] list2=[99,8,0,4,2,1] list3=set(list1).intersection(set(list2)) print(list(list3)) except ValueError: print("error occured") Sort a list without using sort(). try: list2=[99,8,0,4,2,1] for i in range(len(list2)): for j in range(len(list2)-1): if list2[j]>list2[j+1]: list2[j],list2[j+1]=list2[j+1],list2[j] ---i am using bubble sort logic print(list2) except ValueError: print("error occured") #Python #CodingPractice #PythonProgramming #ProblemSolving #DataScienceJourney
Python Practice Progress: 21/50 Questions Solved
More Relevant Posts
-
🐍 Did you know? In Python, there’s a layer that sits above your classes, one that controls how classes themselves are created and behave. It’s called a metaclass. What exactly is a metaclass? - Objects are instances of classes - Classes are instances of metaclasses By default, Python uses type as the metaclass for all classes. But you can create your own metaclasses to customize how classes are defined and constructed. Example 1: Auto-injecting methods The metaclass automatically adds a greet method to the class. class Meta(type): def __new__(cls, name, bases, dct): def greet(self): return f"Hello from {name}!" dct["greet"] = greet return super().__new__(cls, name, bases, dct) class Person(metaclass=Meta): def __init__(self, name): self.name = name p = Person("Olivia") print(p.greet()) # Hello from Person! Example 2: Enforcing class rules Metaclasses can enforce constraints when a class is created. class MainClass(type): def __new__(cls, name, bases, attrs): if "foo" in attrs and "bar" in attrs: raise TypeError(f"Class {name} cannot define both foo and bar") return super().__new__(cls, name, bases, attrs) class SubClass(metaclass=MainClass): foo = 42 # bar = 34 # This would raise an error Example 3: Dynamic class generation class AnimalType: def __init__(self, ftype, items): self.ftype = ftype self.items = items def sub_animal(ftype): class_name = ftype.capitalize() def __init__(self, items): super(self.__class__, self).__init__(ftype, items) globals()[class_name] = type(class_name, (AnimalType,), {"__init__": __init__}) # create classes dynamically [sub_animal(a) for a in ["mammal", "bird"]] Metaclasses are a powerful (and sometimes mysterious) part of Python. Most developers rarely need them, but they are used in frameworks like Django. #Python #Metaclasses #SoftwareEngineering #BackendDevelopment #CleanCode #PythonTips
To view or add a comment, sign in
-
-
Python functions with fixed signatures break the moment you need to forward arguments across abstraction boundaries. *args and **kwargs solve that — and this python tutorial goes well past the syntax. — How CPython actually handles variadic calls at the C level (PyTupleObject, PyDictObject, and why there's a real allocation cost) — Why a defaulted parameter before *args is effectively unreachable via positional calling — and the idiomatic fix — The difference between *args isolating the mapping vs sharing mutable values inside it — ParamSpec (PEP 612) for preserving decorator signatures through the type system — TypedDict + Unpack (PEP 692, Python 3.12) for per-key precision on **kwargs — inspect.Parameter.kind for reading variadic signatures at runtime — the foundation of FastAPI and pytest's dispatch logic — Lambda variadic syntax, functools.wraps, kwargs.setdefault patterns, and common SyntaxErrors caught at parse time Includes interactive quizzes, spot-the-bug challenges, a design decision review, and a 15-question final exam with a downloadable certificate of completion. Full guide: https://lnkd.in/gHkdvCn5 #Python #PythonProgramming #SoftwareDevelopment
To view or add a comment, sign in
-
Slow python ? Meet pybind11 ! It started with a simple curiosity while exploring autograd in Deep Learning frameworks. To better understand how gradients work behind the scenes, we implemented #micrograd by Andrej Karpathy a tiny educational autograd engine written in Python. After building it, a natural question emerged: If Python is slow, how are performance-heavy libraries still so fast? Digging deeper, we discovered that many high-performance Python libraries rely on C++ under the hood, with Python acting as a clean interface. This led us to explore pybind11, a lightweight way to bridge Python and C++ ! We then, - Implemented micrograd in C++ - Exposed it to Python using pybind11 - Generated .so modules using setup.py - Recreated a simplified Python plus C++ architecture This small experiment helped us understand how Python can leverage C++ for performance while maintaining developer productivity.. Also, pybind11 is one of the several alternatives like SWIG, Boost.Python, and Cython that can also be used for language bindings. This exploration was done in collaboration with Kavin Kumar, where we jointly worked on both the medium article and the C++ micrograd implementation. To check our implementation, Github: https://lnkd.in/gz6GBuNV For a deep dive, Explore our article: https://lnkd.in/g2y8KRta PS: Not AI Generated :) #Python #CPP #CPlusPlus #Pybind11 #MachineLearning #DeepLearning #Autograd #Micrograd #PythonPerformance
To view or add a comment, sign in
-
Ever screamed at your screen because Python changed a variable you never touched? Or a function suddenly "remembered" values from previous calls? Or a SyntaxError pointed to a line that looked perfect? These aren't random bugs — they're Python's design decisions in action. And they trip up beginners and experienced devs alike. I wrote the guide I wish existed when I started: "Getting Started with Python: Overview & Real-World Applications" Not another "Python is readable" list — but a practitioner's breakdown of the **8 core surprises** that explain most "why does this behave that way?" moments in your first year. The 8 problems covered: - Terminal says Python doesn't exist (PATH hell) - Error on a line that looks fine (parser vs runtime) - Changing one variable changes another (name binding) - Function modifies input it should only read - Mutable defaults trap — function remembers across calls - "1992" isn't a number (input() strings) - Code runs but nobody understands it (naming/docstrings) - Windows paths break silently (escape sequences/raw strings) Plus: how these same concepts power real-world Python in data science (Pandas views/copies), web (Django/FastAPI), and automation. If you've ever wasted hours debugging a "perfectly logical" Python script — this post gives you the mental model to stop it. Read it here: https://lnkd.in/gcsHx66Q What's the #1 Python surprise that cost you the most time early on? Drop it below — let's commiserate and learn from each other. #Python #LearnPython #PythonBeginners #ProgrammingTips #DataScience #Coding (Full Python Fundamentals series linked inside — 13 articles building from install to production concepts)
To view or add a comment, sign in
-
Python raises no error and produces no warning when an instance attribute shadows a @classmethod. The method is still on the class — it's just hidden from that specific instance. This happens because @classmethod is a non-data descriptor. It defines __get__ but not __set__, which puts it in tier 3 of Python's three-tier attribute lookup. An instance attribute with the same name sits in tier 2 (the instance __dict__) and wins every time. The result: c.create() raises TypeError with a message that never mentions shadowing. The bug can sit undetected for a long time. A new article on PythonCodeCrack covers how the descriptor protocol makes this possible, how to detect an active shadow using vars() and an MRO walk, and six prevention strategies — from naming conventions and __slots__ to ProtectedClassMethod data descriptors and a ProtectedMeta metaclass for hierarchy-wide coverage. There's also an interactive step-through visualizer, a Spot the Bug challenge, and a decision flowchart that routes to the right prevention strategy based on your codebase constraints. https://lnkd.in/ghRPQF9U #Python #PythonProgramming #SoftwareEngineering #DescriptorProtocol #PythonTips
To view or add a comment, sign in
-
Day 6 of learning Python — and today, it clicked. 🐍 Lists. I used to wonder — why not just create separate variables for everything? friend1 = "Priya" friend2 = "Rahul" friend3 = "Meena" And then I realised — what if you had 100 friends? 😅 That’s exactly where Python Lists come in. One variable, all your data, neat and manageable. In today’s blog, I’ve covered everything a beginner needs to get comfortable with lists: ✅ What a list is and how to create one ✅ Indexing and slicing (yes, the [-1] trick is a game changer!) ✅ Adding and removing items — append(), insert(), remove(), pop() ✅ Looping through lists ✅ Combining lists with functions (Days 4 + 5 + 6 finally came together!) ✅ 6 hands-on exercises + a challenge at the end The best part? Lists are everywhere in Python — whether you’re reading files, processing data, or building automation scripts. Learning them well is non-negotiable. If you’re following along from Day 1, this is where things start feeling real. 💪 📖 Read the full blog here 👇 https://lnkd.in/gGDvj-FC Huge thanks to Ajay Kumar Yegireddi and the Mr Cloudbook team for the platform and the encouragement to keep writing. See you on Day 7! 🚀 #Python #PythonForBeginners #100DaysOfCode #MrCloudBook #LearningInPublic #TechCommunity #WomenInTech #PythonLists
To view or add a comment, sign in
-
🚀 **DSA with Python – Recursion Practice** Continuing my **Data Structures & Algorithms with Python** journey, today I practiced more **recursion-based problems** to strengthen my understanding of how recursive calls break problems into smaller subproblems. 📚 **Problems I Practiced** 🔹 **Count Number of Digits (Recursion)** Logic: Repeatedly divide the number by 10 until it reaches 0. Each recursive call counts one digit. 🔹 **Sum of Digits of a Number** Example: 5251 → 5 + 2 + 5 + 1 = 13 Using recursion: `sum(n) = (n % 10) + sum(n // 10)` 🔹 **Reverse a String using Recursion** Example: `"abcd"` → `"dcba"` Recursively reduce the string and build the reversed result step by step. 🔹 Palindrome Check using Recursion Compared characters from the start and end of the string recursively until the middle is reached. Works for both odd and even length strings. 🔹 Reverse a String using Recursion Example: "abcd" → "dcba" Recursively append characters from the end to build the reversed string. 🔹 Sum of All Elements in an Array using Recursion Logic: sum(arr, i) = arr[i] + sum(arr, i+1) Continue until the index reaches the length of the array. 💡 **Key Learnings** ✔ Importance of **base conditions** in recursion ✔ How recursive calls create a **call stack** ✔ Breaking complex problems into **smaller subproblems** ✔ Strengthening **algorithmic thinking** Step by step building stronger foundations in **DSA and problem solving**. #DSA #Python #Recursion #Algorithms #DataStructures #CodingPractice #ProblemSolving #CodingInterview #PythonDeveloper #SoftwareEngineering #BackendDevelopment #LearnInPublic #DeveloperJourney #ContinuousLearning #Programming #TechLearning #100DaysOfCode #CodingJourney
To view or add a comment, sign in
-
-
🚀 Understanding if __name__ == "__main__": in Python (Once and For All!) 👀 You’ve definitely seen this line before: python code: if __name__ == "__main__": But… do you really know why it exists and when to use it? Let’s break it down in a simple, practical way 👇 🧠 The Core Idea When Python imports a file (module), it doesn’t just import functions… 👉 It executes the entire file. Yes — including: - print() statements - input() prompts - Any top-level logic Even if all you wanted was a single function 😅 ⚠️ The Problem Imagine this scenario: You have a file calculator.py with functions and some executable code. Then you import it into another file: python code: import calculator 💥 Suddenly: - It prints messages - It asks for user input - It runs calculations All before your main program continues 👉 Not because you did anything wrong… 👉 But because that’s how Python imports work ✅ The Solution This is where the magic comes in: python code: if__name__=="__main__": ✨ This line gives you control over execution 🔍 How It Works - When you run a file directly → __name__ == "__main__" - When you import the file → __name__ == "module_name" So: 👉 Code inside this block only runs when the file is executed directly 👉 It does NOT run when the file is imported elsewhere 💡 Best Practice Example python codes: def add(a, b): return a+b def subtract(a, b): return a-b if__name__=="__main__": print("This is a simple calculator") x=int(input("Enter a number: ")) y=int(input("Enter another number: ")) print(add(x, y)) print(subtract(x, y)) 🎯 Why This Matters ✔ Keeps your code clean and reusable ✔ Separates logic from execution ✔ Prevents unwanted side effects during imports ✔ Makes your code interview-ready 💼 🧩 Simple Rule to Remember 👉 Write functions at the top 👉 Put execution/testing code inside if __name__ == "__main__": 🏁 Final Thought If your Python file is meant to be: - 🔁 Reusable (imported elsewhere) - ▶️ Executable (run directly) Then this pattern isn’t optional — it’s essential. 💬 Have you ever run into this issue while importing modules? Let’s discuss! #Python #Programming #SoftwareDevelopment #CodingTips #PythonTips #LearnToCode #TechEducation #Developers
To view or add a comment, sign in
-
-
🚀 **DSA with Python – Practice Update** Continuing my **Data Structures & Algorithms with Python** journey, today I worked on problems that strengthened my understanding of **recursion, backtracking, and string manipulation**. 📚 **Problems I Practiced** 🔹 **Letter Combinations of a Phone Number** Given digits (2–9), generate all possible letter combinations based on a phone keypad. 📌 Approach: **Backtracking (Recursion)** * Map digits to characters * Pick → Recurse → Backtrack * Build all possible combinations 🔹 **Subsequence of a Given String** Find all possible subsequences of a string. 📌 Approach: **Pick / Not Pick (Recursion)** * Include current character → Recurse * Exclude current character → Recurse Example: `"abc"` → `["", "a", "b", "c", "ab", "ac", "bc", "abc"]` 💡 **Key Learnings** ✔ Mastered **recursion & backtracking techniques** ✔ Understood **decision-making (pick / not pick)** approach ✔ Improved **string handling & problem-solving skills** ✔ Built stronger **foundations for coding interviews** Consistent practice is helping me move one step closer to mastering **DSA with Python** 💻 #DSA #Python #Algorithms #DataStructures #Recursion #Backtracking #Subsequence #ProblemSolving #CodingPractice #CodingInterview #PythonDeveloper #SoftwareEngineering #BackendDevelopment #LearnInPublic #DeveloperJourney #ContinuousLearning #Programming #TechLearning #100DaysOfCode #CodingJourney
To view or add a comment, sign in
-
-
🚀 Day 22 /30 📝Hollow Patterns #30DaysOfPython Today I practiced Hollow Pattern Programming using Python. I learned how to print hollow shapes by using conditions inside nested loops. This helped me understand how logical conditions ("if" statements) control pattern boundaries. ⭐ 1️⃣ Hollow Square Pattern Example Output: * * * * * * * * * * * * * * * * 💻 Python Code: n = 5 for i in range(1, n+1): for j in range(1, n+1): if i == 1 or i == n or j == 1 or j == n: print("*", end=" ") else: print(" ", end=" ") print() ---------------------------------------------------------------------- ⭐ 2️⃣ Hollow Right Triangle Example Output: * * * * * * * * * * * * 💻 Python Code: n = 5 for i in range(1, n+1): for j in range(1, i+1): if j == 1 or j == i or i == n: print("*", end=" ") else: print(" ", end=" ") print() ---------------------------------------------------------------------- ⭐ 3️⃣ Hollow Pyramid Pattern Example Output: * * * * * * * * * * * * 💻 Python Code: n = 5 for i in range(1, n+1): print(" "*(n-i), end="") for j in range(1, i+1): if j == 1 or j == i or i == n: print("* ", end="") else: print(" ", end="") print() ---------------------------------------------------------------------- 📚 What I Learned Today ✔ Creating hollow patterns using conditions ✔ Using "i" and "j" positions to control pattern edges ✔ Understanding boundary logic in pattern programming ✔ Improving problem-solving skills with nested loops ✔ Combining loops and conditions effectively ---------------------------------------------------------------------- 💡 Key Takeaway Hollow patterns are a great way to practice conditional logic and nested loops, which are very important for improving programming skills. #Day22✅ Step by step, my Python logic building is getting stronger 🚀 #Python #30DaysOfPython #CodingJourney #PatternProgramming #LearningDaily
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