One-Line Sorting with Custom Lambda Key (Sort Integers by The Number of 1 Bits) 💯 || O(N log N) || Just tackled a fun bit-manipulation and sorting problem on LeetCode (Problem 1356), and I wanted to share a super clean, Pythonic way to solve it! 🐍 🎯 The Problem: Sort an array of integers based on the number of 1s in their binary representation. If two numbers have the same number of 1s, sort them by their decimal value. 💡 The Approach: Instead of writing a complex custom comparator, Python’s built-in sorting handles multi-level conditions beautifully. By passing a list [primary_condition, secondary_condition] to the key argument, Python sorts by the first element and automatically falls back to the second if there's a tie. Here is the one-liner: Python class Solution: def sortByBits(self, arr: List[int]) -> List[int]: return sorted(arr, key=lambda x: [bin(x).count('1'), x]) 📊 Complexity: Time: O(N log N) — Python's Timsort algorithm does the heavy lifting, and counting bits for 32-bit integers takes O(1) time. Space: O(N) — Using sorted() creates a new list. Pro-Tip: If you want to optimize for space, you can swap sorted(arr, ...) for arr.sort(...) to sort the array in-place! What is your favorite Python built-in function or one-liner tip? Let me know in the comments! 👇 #Python #LeetCode #Algorithms #CodingInterviews #SoftwareEngineering #DataStructures
Sort Integers by Binary 1s and Decimal Value
More Relevant Posts
-
𝐍𝐮𝐦𝐏𝐲 𝐁𝐨𝐨𝐥𝐞𝐚𝐧 𝐓𝐫𝐚𝐩 I’m still at the very beginning of my Python journey. But even with my tiny amount of experience, I already hit a subtle NumPy trap that can easily sneak into real code. Python is full of surprises — even at the very beginning It happens when you create an untyped NumPy array and fill it with a function that should return booleans… …but sometimes returns 𝙉𝙤𝙣𝙚 when processing fails. At first, you expect a clean boolean array — because the function normally returns 𝙏𝙧𝙪𝙚 or 𝙁𝙖𝙡𝙨𝙚. But NumPy has other plans. Here’s the trap 👇 🟥 𝟏) 𝐔𝐧𝐭𝐲𝐩𝐞𝐝 𝐚𝐫𝐫𝐚𝐲 + 𝐚 𝐟𝐮𝐧𝐜𝐭𝐢𝐨𝐧 𝐭𝐡𝐚𝐭 “𝐬𝐡𝐨𝐮𝐥𝐝” 𝐫𝐞𝐭𝐮𝐫𝐧 𝐛𝐨𝐨𝐥𝐞𝐚𝐧𝐬 𝒂𝒓𝒓 = 𝒏𝒑.𝒆𝒎𝒑𝒕𝒚(10) # 𝒏𝒐 𝒅𝒕𝒚𝒑𝒆 𝒂𝒓𝒓[𝒊] = 𝒎𝒚_𝒇𝒖𝒏𝒄() # 𝑻𝒓𝒖𝒆 / 𝑭𝒂𝒍𝒔𝒆 ... 𝒐𝒓 𝑵𝒐𝒏𝒆 You expect a clean boolean array because the function usually returns 𝙏𝙧𝙪𝙚/𝙁𝙖𝙡𝙨𝙚. But if even one value is 𝙉𝙤𝙣𝙚, NumPy must pick a type that can hold all values. 🟦 𝟐) 𝐍𝐮𝐦𝐏𝐲 𝐬𝐢𝐥𝐞𝐧𝐭𝐥𝐲 𝐬𝐰𝐢𝐭𝐜𝐡𝐞𝐬 𝐭𝐨 𝐝𝐭𝐲𝐩𝐞=𝐨𝐛𝐣𝐞𝐜𝐭 𝒂𝒓𝒓𝒂𝒚([𝑻𝒓𝒖𝒆, 𝑭𝒂𝒍𝒔𝒆, 𝑵𝒐𝒏𝒆, ...], 𝒅𝒕𝒚𝒑𝒆=𝒐𝒃𝒋𝒆𝒄𝒕) Impact: no vectorization logical operations break masks behave unpredictably performance collapses You think you have a NumPy boolean array. You actually have a Python object array. 🟩 𝟑) 𝐓𝐡𝐞 𝐬𝐢𝐥𝐞𝐧𝐭 𝐜𝐨𝐧𝐯𝐞𝐫𝐬𝐢𝐨𝐧 𝐭𝐫𝐚𝐩 Trying to fix it: 𝒂𝒓𝒓 = 𝒏𝒑.𝒆𝒎𝒑𝒕𝒚(10, 𝒅𝒕𝒚𝒑𝒆=𝒃𝒐𝒐𝒍) 𝒂𝒓𝒓[𝒊] = 𝒎𝒚_𝒇𝒖𝒏𝒄() NumPy converts: 𝑵𝒐𝒏𝒆 → 𝑭𝒂𝒍𝒔𝒆 (silently) Impact: 👉you lose the meaning of “no result” 👉your data becomes wrong 👉the bug becomes invisible ⭐ 𝐓𝐚𝐤𝐞𝐚𝐰𝐚𝐲 Same code. Same function. Two completely different arrays. NumPy’s dtype inference can hide subtle bugs — and I found this one with almost no Python experience. 𝐂𝐮𝐫𝐢𝐨𝐮𝐬 𝐭𝐨 𝐤𝐧𝐨𝐰: 👉 Have you ever run into this behavior? 👉 Or another NumPy dtype surprise? #python #numpy #datascience #cleanCode #devTips #programming
To view or add a comment, sign in
-
-
Day 24: Iterators — The Engine Behind the Loop ⚙️ In Python, we often talk about "looping over data." But how does Python actually keep track of where it is in a list of 1 million items? It uses the Iterator Protocol. 1. Iterable vs. Iterator (The "Book" vs. The "Bookmark") Iterable: Any object you can loop over (List, String, Dictionary). Think of it as a Book. It contains all the data, but it doesn't "know" which page you are on. Iterator: A special object that represents a stream of data. Think of it as a Bookmark. It knows exactly where you are and what comes next. 2. The Tools: iter() and next() You can turn any Iterable into an Iterator using these two built-in functions: iter(my_list): Creates the "Bookmark" for that list. next(my_iterator): Moves the bookmark to the next "page" and returns the value. numbers = [10, 20] my_iter = iter(numbers) print(next(my_iter)) # Output: 10 print(next(my_iter)) # Output: 20 # print(next(my_iter)) # Error: StopIteration (The book is finished!) 3. Does it store data in memory? 🧠 This is the "Senior Engineer" secret. Lists/Tuples store all their data in memory at once. If you have 1 billion numbers, your RAM will crash. Iterators (and specifically Generators) are "Lazy." They don't store the whole list; they only calculate or fetch the next item when you ask for it. 💡 The Engineering Lens: This is why we use Iterators for massive datasets (like reading a 10GB log file). We process one line at a time, keeping our memory usage near zero! 4. The StopIteration Exception When an iterator runs out of items, it doesn't return None or 0. It raises a StopIteration error. 💡 The Engineering Lens: A for loop is actually just a "Fancy While Loop" that calls next() repeatedly and automatically handles the StopIteration error so your program doesn't crash. #Python #SoftwareEngineering #ComputerScience #MemoryManagement #Iterators #LearnToCode #CodingTips #TechCommunity #BackendDevelopment
To view or add a comment, sign in
-
🐍 `__iter__()` & `__next__()` — How Python Loops Actually Work ******************************* Every time a `for` loop runs in Python, two methods run silently behind it. The distinction worth understanding: 1️⃣ An iterable has `__iter__()` — it can be looped over. 2️⃣ An iterator has both `__iter__()` and `__next__()` — it tracks position. Every list, string, file, and dict you loop over follows exactly this two-method protocol. ——————————————————————— When you implement it yourself, your objects become first-class citizens of the Python ecosystem — compatible with `for`, `list()`, `sum()`, `zip()`, and everything else. The real power is lazy evaluation. An iterator yields one value at a time. It does not load everything into memory upfront. That distinction becomes significant when the data is large. The visual guide below shows how both methods work, what a `for` loop actually does under the hood, and a real-world lazy CSV reader that handles large files without loading them into RAM. This series has covered `__init__()`, `__call__()`, `__enter__()` / `__exit__()`, `__del__()`, and `__str__()` / `__repr__()` — this one reveals the engine behind every loop you write. Next in the series → `__getitem__()` and `__setitem__()` Have you ever built a custom iterator? What was the use case? #Python #SoftwareEngineering #PythonDevelopment #sourcescodedev
To view or add a comment, sign in
-
-
Stop writing try/finally blocks. Use context managers instead. I see this pattern everywhere in Python codebases: connection = get_db_connection() try: result = connection.execute(query) finally: connection.close() Nothing wrong with it — until you have 15 resources to manage across your project. Here's the cleaner version with contextlib: from contextlib import contextmanager @contextmanager def db_connection(): conn = get_db_connection() try: yield conn finally: conn.close() with db_connection() as conn: result = conn.execute(query) Why this is better: → Resource cleanup logic lives in ONE place → You can't forget to close — it's automatic → Stack multiple with a single `with` statement → Works with async too (`@asynccontextmanager`) My favorite use case: temporary environment changes in tests. @contextmanager def override_settings(**kwargs): old = {k: getattr(settings, k) for k in kwargs} for k, v in kwargs.items(): setattr(settings, k, v) try: yield finally: for k, v in old.items(): setattr(settings, k, v) Small abstraction. Massive reduction in bugs. What's your favorite Python pattern that most people underuse? 👇 #Python #Programming #BackendDevelopment #SoftwareEngineering #CleanCode
To view or add a comment, sign in
-
🚀 “𝗠𝘂𝘁𝗮𝗯𝗹𝗲 𝗼𝗿 𝗜𝗺𝗺𝘂𝘁𝗮𝗯𝗹𝗲?” — 𝗧𝗵𝗲 𝗣𝘆𝘁𝗵𝗼𝗻 𝗖𝗼𝗻𝗰𝗲𝗽𝘁 𝗧𝗵𝗮𝘁 𝗧𝗿𝗶𝗽𝘀 𝗨𝗽 𝗘𝘃𝗲𝗻 𝗣𝗿𝗼𝘀 In Python, 𝙚𝙫𝙚𝙧𝙮𝙩𝙝𝙞𝙣𝙜 𝙞𝙨 𝙖𝙣 𝙤𝙗𝙟𝙚𝙘𝙩 — but not every object behaves the same in memory. That’s where 𝗠𝘂𝘁𝗮𝗯𝗶𝗹𝗶𝘁𝘆 and 𝗜𝗺𝗺𝘂𝘁𝗮𝗯𝗶𝗹𝗶𝘁𝘆 come in.👇 💡 Think of variables not as boxes, but as labels that point to objects in memory. 🧊 𝗜𝗺𝗺𝘂𝘁𝗮𝗯𝗹𝗲 𝗢𝗯𝗷𝗲𝗰𝘁𝘀 — fixed once created You can’t really "change" them — when you try, Python quietly builds a new object behind the scenes. 👉 Examples: 𝙞𝙣𝙩, 𝙛𝙡𝙤𝙖𝙩, 𝙨𝙩𝙧, 𝙩𝙪𝙥𝙡𝙚, 𝙗𝙤𝙤𝙡 𝗖𝗼𝗱𝗲 username = "John" # Points to Object A username = "tea" # Now points to Object B — Object A is garbage collected 🔍 Interview Tip: You didn’t actually modify "John" — Python simply changed where username points! 🔁 𝗠𝘂𝘁𝗮𝗯𝗹𝗲 𝗢𝗯𝗷𝗲𝗰𝘁𝘀 — flexible and editable You can modify them in place, without creating a new object. 👉 Examples: 𝙡𝙞𝙨𝙩, 𝙙𝙞𝙘𝙩, 𝙨𝙚𝙩 𝗖𝗼𝗱𝗲 letters = ["P", "y", "t", "h", "o", "n"] # Points to Object A letters[0] = "p" # Edited in place — still points to same Object A You can add, remove, or update values without changing the memory reference. 🧠 Quick Recap Variables = labels, not containers Immutable → 🔄 new object created Mutable → ✏️ same object modified Old objects → 🧹 cleaned by Python’s garbage collector 🔖 #Python #CodingTips #SoftwareEngineering #DeveloperInsights #LearnPython #PythonCommunity #ProgrammingConcepts
To view or add a comment, sign in
-
Day 18: Scope and Precision — The Limits of Logic 🌐 As your programs grow, you'll start having variables with the same names in different places. How does Python know which one to use? And when doing math, how many decimals can Python actually "remember"? 1. Local vs. Global Scope Think of Scope as the "area of visibility" for a variable. Global Scope: Variables defined at the top level (outside any function). They can be read from anywhere in your script. Local Scope: Variables defined inside a function. They only exist while that function is running. Once the function ends, the variable is deleted. 💡 The Engineering Lens: Avoid using too many Global variables. If every function can change a variable, it becomes a nightmare to track down bugs. Keep data "Local" whenever possible! 2. The LEGB Rule: Python’s Search Engine When you call a variable name, Python searches in a very specific order to find it. This is the LEGB rule: Local: Inside the current function. Enclosing: Inside any nested "parent" functions. Global: At the top level of the file. Built-in: Python’s pre-installed names (like len or print). 3. Precision: The Decimal Limit When you use a Float (a decimal number), Python has to fit that number into a fixed amount of memory. Maximum Precision: Python floats are typically "double-precision" (64-bit). This means they can hold about 15 to 17 significant decimal digits. The Default: When you perform a calculation, Python will show as many decimals as are relevant, but it stops being accurate after that 15–17 digit mark. 💡 The Engineering Lens: Because of this limit, 0.1 + 0.2 often equals 0.30000000000000004. If you are building a banking app or a scientific tool where you need infinite precision, don't use floats! Use Python’s decimal module instead. #Python #SoftwareEngineering #CleanCode #ProgrammingTips #DataPrecision #LearnToCode #TechCommunity #PythonDev
To view or add a comment, sign in
-
Stop treating Python variables like boxes. They are actually labels. Understanding this architectural shift is the difference between writing robust code and chasing "ghost" bugs for hours. Here is how to master your data architecture in Python: Know your materials: Immutable types (like int, str, and tuple) are like stone—they cannot be changed in place. Mutable types (like list and dict) are like clay—they can be reshaped without creating a new object. The "Hashability" Price: Only immutable objects are hashable, meaning they can serve as dictionary keys or set elements. If you try to use a mutable list as a key, Python will throw a TypeError. The Default Argument Trap: Never use a mutable type (like []) as a function's default argument. These are created only once at definition, meaning every call to that function will share and modify the same list. Copy with Caution: When dealing with nested structures, a "shallow copy" only creates a new outer container while sharing the inner objects. Always be explicit and use copy.deepcopy() if you need a completely independent version. The Golden Rule: Use is None for identity checks rather than == None to ensure faster, more reliable null handling. Are you building with stone or clay today? #Python #DataArchitecture #CodingTips #SoftwareEngineering
To view or add a comment, sign in
-
Today I explored some important concepts in NumPy, I learned 👇 1. Arrays NumPy arrays are lists of numbers used for fast mathematical operations. Example: Python import numpy as np arr = np.array([1, 2, 3]) 🔹 2. Broadcasting Broadcasting means applying one value to all elements in the array automatically. Example: Python np.array([1,2,3]) + 5 # → [6 7 8] 🔹 3. Axis Axis tells which direction an operation runs. axis=0 → column-wise axis=1 → row-wise Example: Python arr.sum(axis=0) 🔹 4. Slicing Slicing means cutting a part of an array. Example: Python arr = np.array([10,20,30,40]) arr[1:3] # → [20 30] 🔹 5. Stacking Stacking means joining arrays. Example: Python np.hstack((a, b)) np.vstack((a, b)) 🔹 6. Random Values NumPy can create random numbers easily. Example: Python np.random.rand(2,3) 🔹 7. Reshape Reshape changes the shape of an array without changing data. Example: Python np.arange(6).reshape(2,3) # → [[0 1 2] # [3 4 5]]
To view or add a comment, sign in
-
Day 17 – Strings, Lists & Practical Logic Building in Python Today’s session was a mix of real-world logic building and deeper practice with strings and lists in Python. I started with a simple electricity bill calculation program using conditional statements. It helped me understand how tier-based logic works in real-life scenarios and how to structure conditions properly using if-elif-else. Strings – More Practice Revised and practiced important string methods: upper() and lower() for case conversion isupper() and islower() for validation capitalize() vs title() replace() with control over number of replacements This reinforced how strings are immutable and how every operation returns a new modified string. Lists – Slicing & Methods in Depth Worked extensively on list operations and understood the difference between modifying and non-modifying methods. Slicing Practice: Normal slicing Step slicing Reverse slicing Skipping elements using step values List Methods Explored: append() → add single element extend() → add multiple elements from iterable insert() → add element at specific index remove() → remove first occurrence pop() → remove by index (returns removed value) clear() → empty the list index() → find position of element sort() → modifies original list sorted() → returns new sorted list reverse() → reverse list order join() → join list elements into a string I also observed: How insert() behaves with negative and out-of-range indexes Difference between sort() and sorted() How extend() works differently with list, tuple, and set Key Takeaways Understanding method behavior is more important than just memorizing syntax Some methods modify the original list, others return new values Real learning happens when testing edge cases Logic building is improving step by step Day 17 was more about strengthening fundamentals and building clarity in how Python handles data structures. #Python #PythonLists #PythonStrings #ProgrammingBasics #DataStructures #CodingPractice #DailyLearning #ProblemSolving #LearnToCode #SoftwareDevelopment
To view or add a comment, sign in
-
Ever explained Duck Typing in Python to someone and watched their face go from 😃 → 🤯 in 3 seconds? Here’s how I tried explaining it to a friend: Friend: “How does Python know if something is a duck?” Me: Python doesn’t care if it’s a duck 🦆, a robot 🤖, or a developer pretending to work on Friday afternoon 😅 If it walks like a duck and quacks like a duck, Python just says: "Cool… must be a duck." Example 👇 class Duck: def quack(self): print("Quack!") class Person: def quack(self): print("I can imitate a duck!") def make_it_quack(obj): obj.quack() make_it_quack(Duck()) make_it_quack(Person()) Python: "Both quack? Perfect. I’m not asking for ID." Meanwhile in some other languages: "Excuse me sir, please submit 4 forms, 2 interfaces, and a type certificate before quacking." 🧾 That’s the beauty of Python — behavior matters more than type. So remember: In Python, nobody asks what you are. They only check what you can do. And honestly… that’s a life lesson too. 😄 #Python #DuckTyping #ProgrammingHumor #LearnToCode #PythonDeveloper #CodingLife #SoftwareEngineering #TechHumor #DeveloperLife
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