🚀 Day 9 of #100DaysOfCode — Finding the Sum of the Smallest Numbers in Python Today I explored two different approaches to solve a simple but important problem: 👉 Find the sum of the smallest N numbers in a list ✅ Approach 1: Pythonic & Efficient numbers = [5, 2, 9, 1, 7] n = 2 result = sum(sorted(numbers)[:n]) print(result)🔹 How it works: sorted(numbers) → sorts the list[:n] → picks the smallest n elementssum() → adds them up💡 Clean, readable, and perfect for most use cases. ✅ Approach 2: Manual Logic (Without Built-ins) arr = [5, 2, 9, 4, 3, 5] N = 2 total = 0 data = len(arr) for k in range(N): min_index = 0 for i in range(1, data): if arr[i] < arr[min_index]: min_index = i total += arr[min_index] arr[min_index] = float('inf') print("Sum of smallest", N, "numbers:", total)🔹 How it works: Repeatedly finds the smallest elementAdds it to totalMarks it as used (by setting to infinity)💡 Great for understanding core logic and algorithm design 🔍 Key Takeaways ✔️ Built-in functions save time and reduce complexity ✔️ Manual approach helps strengthen problem-solving skills ✔️ Always balance readability vs control 💬 Best Comment Insight “Don’t just learn shortcuts — understand what’s happening under the hood. That’s where real growth happens.” #Python #CodingJourney #30DaysOfCode #LearnToCode #Programming #Developers #ProblemSolving #PythonBasics
Python Sum of Smallest Numbers: Efficient & Manual Approaches
More Relevant Posts
-
Most developers use __init__ every day. But here’s the catch: We use it so often that we stop questioning how objects are actually created. And that’s where __new__ quietly gets ignored. The truth is: 👉 __𝐧𝐞𝐰__ creates the object 👉 __𝐢𝐧𝐢𝐭__ initializes the object Python doesn’t create objects in one step. It happens in two phases: 1️⃣ Memory is allocated → __new__ 2️⃣ Object is configured → __init__ A quick example: class Example: def __new__(cls): print("Creating instance") return super().__new__(cls) def __init__(self): print("Initializing instance") obj = Example() 𝘖𝘶𝘵𝘱𝘶𝘵: Creating instance Initializing instance Here’s the part most people never think about 👇 You’ve probably never written __new__. Yet your objects still get created perfectly. Why? Because Python is already doing this behind the scenes: obj = MyClass.__new__(MyClass) MyClass.__init__(obj) And if you don’t define __new__, Python uses: object.__new__() We treat __init__ like a constructor. But technically… it isn’t. 👉 𝑻𝒉𝒆 𝒓𝒆𝒂𝒍 𝒄𝒐𝒏𝒔𝒕𝒓𝒖𝒄𝒕𝒐𝒓 𝒊𝒔 __𝒏𝒆𝒘__. ⚡ Why __new__ matters: - Controls object creation - Used in Singleton patterns - Important for immutable types (int, str, tuple) - Can even return a different object ⚡ What __init__ actually does: - Just initializes the already-created object - Cannot create or return a new instance - Always returns None 💡 Real takeaway: We rely on __init__ so much that we rarely think about what happens before it. Understanding __new__ is what shifts you from: 👉 writing Python code to 👉 understanding how Python actually works Once you see it, you can’t unsee it 🙂 #Python #PythonProgramming #SoftwareDevelopment #BackendDevelopment #Coding #Programming #LearnToCode #DeveloperMindset #TechCareers #SoftwareEngineer #CleanCode #ProgrammingConcepts
To view or add a comment, sign in
-
-
📅 Day 5 of Python — and today was all about putting knowledge to the test! 💪 Instead of learning something new, I took on a full practice session covering everything I've studied so far on Python's core data structures. 🧪 Here's what I worked through: ✅ Lists — creating, slicing, methods like append(), extend(), insert(), pop(), remove(), and sort() ✅ List Comprehensions — squares, filters, tuple pairs, and more ✅ Tuples — declaration, immutability (yes, I triggered the TypeError 😅), unpacking, and zip() ✅ Sets — deduplication, membership checks, add/remove/discard, and set operations like union, intersection, difference & symmetric difference ✅ Dictionaries — key-value access, get(), items(), keys(), values(), nested dicts, and updating/deleting entries ✅ Dictionary Comprehensions — building mappings with filters ✅ Applied Problems — frequency maps, common elements using sets, zip() with conditional logic The practice set had 30+ exercises and solving each one back-to-back really helped solidify the concepts rather than just reading about them. Key takeaway from today: You don't truly understand a concept until you've broken it, debugged it, and fixed it yourself. 🔧 On to Day 6! 🚀 #Python #100DaysOfCode #DataStructures #LearningInPublic #CodingJourney #PythonProgramming
To view or add a comment, sign in
-
Day 10/365: Building a List from User Input & Finding Basic Stats 🔢📥 Today I wrote a Python program that takes numbers from the user, stores them in a list, and then calculates some basic statistics: sum, average, minimum, and maximum. What the code does step by step: First, I ask the user how many elements they want to enter and store that in n. I create an empty list l and a variable total to keep track of the sum. Using a for loop, I take n inputs from the user: Each number is added to the list using append(). At the same time, I keep adding each number to total to calculate the sum. After the loop: I print the full list. I print the sum using the total variable. Then I calculate the average as total / n and print it. To find the minimum and maximum: I start by assuming both min and max are the first element of the list. I loop through the list and update min if I find a smaller value. Similarly, I update max if I find a larger value. In the end, I print the minimum and maximum numbers in the list. What I learned from this exercise: How to take multiple inputs from a user and store them in a list. How to maintain a running sum while taking inputs. How to manually compute average, minimum, and maximum without using built‑in functions like sum(), min(), or max(). How loops and variables can work together to build simple but useful statistics — a basic idea used a lot in data analysis. Day 10 done ✅ 355 more to go. If you have ideas like extending this to find median, mode, or standard deviation, send them to me — I’d love to try them next. #100DaysOfCode #365DaysOfCode #Python #LogicBuilding #Lists #UserInput #CodingJourney #LearnInPublic #AspiringDeveloper
To view or add a comment, sign in
-
-
Day 7 Today’s focus was on mastering the "Big Three" of Python collections: Tuples Sets Dictionaries. Here’s a breakdown of the key takeaways from my latest session on Sololearn: 1️⃣ Tuples (Immutability is Key! 🔒) Unlike lists, tuples are immutable, meaning once they are created, they cannot be changed. This makes them perfect for: Storing data that should remain constant (like coordinates or dates). Tuple Unpacking: Using the * operator to flexibly assign multiple elements to a single variable as a list (Game changer for clean code!). 2️⃣ Sets 💎 When you need to ensure every item in your collection is unique, Sets are the go-to. They are perfect for filtering out duplicates and performing mathematical set operations like unions and intersections. 3️⃣ Dictionaries 📖 I explored the fundamental concept of key-value pairs. Dictionaries are: Mutable: You can add or update items using the .update() method. Highly Searchable: Using the .get() function allows for safe data retrieval without crashing the program if a key is missing. Iterative: Easily loop through keys, values, or items to process complex data sets. 4️⃣ Next Stop: List Comprehensions ⚡ I’m just starting to scratch the surface of List Comprehensions—a much more "Pythonic" and efficient way to create and manipulate lists in a single line of code. Building a solid foundation in these data structures is making me a more confident programmer every day. If you’re a fellow learner or a Python pro, what’s your favorite "hidden gem" tip for working with dictionaries? Let’s discuss! 👇 #Python #CodingJourney #DataScience #WebDevelopment #ContinuousLearning #Sololearn #Programming #TechCommunity #PythonDeveloper
To view or add a comment, sign in
-
-
I did not expect a Python topic about “unique items” to feel this useful… but sets changed that fast. 🐍 Day 7 of my #30DaysOfPython journey was all about sets, and this one felt different because it was less about storing data and more about controlling it. A set is an unordered collection of distinct items. It cannot hold duplicates, which makes it super handy in real-world coding. Today I explored: 1. Creating sets with set() built-in function and {} 2. Checking length with len() 3. Using in to check if an item exists 4. Adding items with add() to add a single item and update() for multiple items 5. Removing items with remove() (raise error if item not present), discard() (does not raise error), and pop() (removes a random item) 6. Clearing a set with clear() 7. Deleting a set with del 8. Converting a list to a set to remove duplicates 9. Set operations like union(), intersection(), difference(), and symmetric_difference() 10. Checking issubset(), issuperset(), and isdisjoint() What made sets interesting to me today was how practical they are when you want uniqueness, comparison, or clean data without duplicates. They may look simple on the surface, but they solve a very specific kind of problem really well. Which Python data type has surprised you the most so far: lists, tuples, or sets? Github Link - https://lnkd.in/eJfTX-HQ #Python #LearnPython #CodingJourney #30DaysOfPython #Programming #DeveloperJourney
To view or add a comment, sign in
-
🏗️ Beyond "It Works": Writing Maintainable Python One of the biggest shifts in my coding journey has been moving away from long, "flat" scripts and toward Modular Programming. Instead of writing one giant block of code, I’ve started breaking my logic into small, reusable functions. Why the change? Separation of Concerns: My math logic (calculating totals) is now separate from my formatting logic (adding currency symbols). Readability: The main script now reads like a story. Instead of staring at complex f-strings, I just see format_currency(). Future-Proofing: If I need to change the currency to Euros or update a tax calculation, I only change it in one place, not everywhere in the script. The Refactored Logic: Python import pandas as pd def calculate_total(quantity, price): """Calculate total for a single item""" return quantity * price def format_currency(amount): """Format number as currency for reports""" return f"${amount:,.2f}" # --- Main Workflow --- df = pd.read_csv('data/sales.csv', skipinitialspace=True) # Using our functions to clean and transform data df['total'] = df['quantity'] * df['price'] df['display_total'] = df['total'].apply(format_currency) print(df[['product', 'display_total']]) It’s a small structural change that makes a massive difference as projects scale. High-quality code isn't just about the output; it's about how easy it is for the next person (or "future me") to read and maintain. #Python #CleanCode #ProgrammingTips #DataScience #LearningToCode #SoftwareEngineering #Automation
To view or add a comment, sign in
-
Day 15/365: Merging Two Dictionaries with Summed Values in Python 🧮🔗 Today I worked on a very common real-world task: merging two dictionaries where overlapping keys should have their values added together. 🧠 What this code does: I start with two dictionaries: d1 = {1: 10, 2: 20, 3: 30} d2 = {3: 40, 5: 50, 6: 60} Each key can represent something like: a product ID with its total sales, a student ID with total marks, a user ID with total points. The goal is to combine d2 into d1: If a key from d2 already exists in d1, I add the values. If the key doesn’t exist in d1, I insert it. Step by step: I loop over each key i in d2: for i in d2: For each key: If i is already a key in d1: I update d1[i] by adding d2[i] to it. Otherwise: I create a new entry in d1 with that key and its value from d2. After the loop finishes, d1 contains the merged result. For the given dictionaries: Key 3 exists in both, so its values are added: 30 + 40 = 70. Keys 5 and 6 only exist in d2, so they are added as new keys. Final output: {1: 10, 2: 20, 3: 70, 5: 50, 6: 60} 💡 What I learned: How to merge two dictionaries manually using a loop and conditions. How to update values in a dictionary when keys overlap. How this pattern appears in real data tasks like: combining monthly reports, merging user activity stats, aggregating counts from multiple sources. Next, I’d like to explore: Handling much larger dictionaries efficiently. Using dictionary methods like update() or Counter from collections to compare approaches. Trying the same logic with string keys (like product names) instead of numbers. Day 15 done ✅ 350 more to go. Got any other dictionary + loop problems (like counting frequencies from multiple sources or merging configs)? Drop them in the comments—I’d love to try them next. #100DaysOfCode #365DaysOfCode #Python #Dictionaries #DataStructures #LogicBuilding #CodingJourney #LearnInPublic #AspiringDeveloper
To view or add a comment, sign in
-
-
🚀 Solved: Group Anagrams Problem (LeetCode) Today I worked on an interesting problem — grouping anagrams efficiently using Python. 💡 Approach: I used a hashmap (dictionary) where: The key is the sorted version of each word The value is a list of words (anagrams) matching that key Example: "eat", "tea", and "ate" → all become "aet" after sorting → grouped together 🧠 Key Insight: Sorting each string gives a unique identifier for all its anagrams. ⚙️ Time Complexity: Sorting each word takes O(k log k) For n words → O(n * k log k) 📦 Space Complexity: O(n * k) for storing grouped anagrams ✅ Result: Accepted ✔️ Runtime: 5 ms (faster than ~99% submissions) 📈 Growth & Consistency: Improving step by step by solving problems daily and focusing on writing clean and optimized code. Small consistent efforts are helping me build stronger problem-solving skills and deeper understanding of DSA. 🔁 Staying consistent is the real game changer! #Python #DSA #LeetCode #Coding #ProblemSolving #Consistency #Growth #LearningJourney
To view or add a comment, sign in
-
-
🚀 Built a simple Python script to clean up my messy Downloads folder! We all download files daily, and things get cluttered fast. So I wrote a quick automation script using Python to organize files into folders like Images, Documents, Archives, etc. 💡 Here’s the code: ```python from pathlib import Path import shutil # Folder to organize source = Path("C:/Users/YourName/Downloads") # File type mapping folders = { ".jpg": "Images", ".png": "Images", ".pdf": "Documents", ".zip": "Archives", ".exe": "Installers" } for file in source.iterdir(): if file.is_file(): folder_name = folders.get(file.suffix.lower()) if folder_name: destination = source / folder_name destination.mkdir(exist_ok=True) shutil.move(str(file), destination / file.name) ``` ⚡ What it does: * Scans your Downloads folder * Detects file types * Creates folders automatically * Moves files to the right place Sometimes, small automations like this can save a lot of time and keep your system organized. #Python #Automation #Coding #Developers #Productivity #Backend
To view or add a comment, sign in
-
Today's topic: recursion. A function that calls itself. Sounds simple, right? Here are two ways to add up a list of numbers: Without recursion — honest, reliable, easy to follow: python def suma(lista): suma = 0 for i in range(0, len(lista)): suma = suma + lista[i] return suma print(suma([6,3,4,2,10])) # 25 With recursion — elegant, almost poetic... and a little terrifying: python def suma(lista): if len(lista) == 1: return lista[0] else: return lista[0] + suma(lista[1:]) print(suma([6,3,4,2,10])) # 25 Same result. Two completely different roads to get there. The recursive version looks more "pro" — but if you forget to define when it stops, the function calls itself forever. Literally. Forever. 💀 So yes, it's getting challenging. And yes, recursion feels more elegant to write. But I'm not ready to fully trust something that could loop into oblivion if I blink wrong. Lesson of the day: simple is not the same as bad. And documenting the moments that confuse you? That's part of learning too. #Python #LearningToCode #DaysOfCode #PythonProgramming #CodingJourney #Recursion #BeginnerCoder #TechLearning #CodeNewbie #LinkedInLearning
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