🚀Day 2/100: The hidden cost of Python lists and "infinite" loops. 🔄 Day 2 of my 100-Day DSA & AI Engineering journey. Today’s focus: Array Manipulation & Memory Allocation. In Python, list.append() feels magic. But under the hood, it’s expensive. When a dynamic array runs out of space, it has to: 1. Allocate a larger block of memory. 2. Copy all existing elements to the new block. 3. Delete the old block. In high-performance AI pipelines (like building batches for a DataLoader), these "hidden copies" kill performance. Day 2: Concatenation & Modulo Arithmetic Challenge: LeetCode [1929] Concatenation of Array. The task was to double an array (concatenate it with itself). Instead of just using the + operator, I explored the Index Mapping approach using Modulo Arithmetic (%). 💡 The Engineering Insight: By using i % n, I can map any index $i$ back to the original range $[0, n-1]$. If length $n = 3$, index $0 \to 0$, index $3 \to 0$. This creates a "Circular Buffer" logic. Why this matters for AI: This pattern is foundational for: Data Augmentation: duplicating datasets efficiently. RNNs & Streaming: handling cyclic data streams. Ring Buffers: implementing Replay Buffers in Reinforcement Learning. Resources: Solved LeetCode [1929] and analyzed the memory overhead of concatenation vs. pre-allocation. Two days down. The foundation is set. 🧱 #100DaysOfCode #Python #DSA #ArtificialIntelligence #MachineLearning #LeetCode #MemoryManagement #Day2
Python List Optimization: Array Manipulation & Memory Allocation
More Relevant Posts
-
🚀 Day 11 – Learning Dictionaries, Tuples & Their Differences in Python Today I explored Dictionaries and Tuples in Python and understood how they are used to store and manage data efficiently. 🔹 Tuple A tuple is an ordered and immutable collection. Once created, its values cannot be changed. 🔹 Dictionary A dictionary stores data in key–value pairs, making it very useful for mapping relationships between data. 🔹 items() Method I also learned about the items() method, which returns dictionary data as key–value pairs, often used when iterating through dictionaries. While learning this, a question came to my mind: Why do we sometimes convert a dictionary into a list of tuples? I found that converting a dictionary to tuples is helpful when: • Iterating through key-value pairs easily • Preparing data for sorting • Working with functions that require tuple-based structures 📚 References: https://lnkd.in/e5-CGnPc https://lnkd.in/eqNcPwaM https://lnkd.in/eqH7Ack8 Step by step strengthening my Python fundamentals on my learning journey toward Data Engineering and AI. #Python #DataEngineering #LearningJourney #SelfLearning #AI #CareerGrowth
To view or add a comment, sign in
-
-
🚀 Day 5 of My Artificial Intelligence Learning Journey Today I explored some powerful Python concepts that make code more efficient and expressive, especially when working with data. Here’s what I learned today: 🔹 List Comprehension – A concise way to create and transform lists. 🔹 Set Comprehension – Used to build sets quickly while ensuring unique elements. 🔹 Dictionary Comprehension – Efficient way to create dictionaries using loops and conditions. 🔹 Lambda Functions – Small anonymous functions useful for short operations. 🔹 Analytical Functions – Functions used to perform calculations and analysis on data. 🔹 Aggregate Functions – Functions like "sum()", "min()", "max()", and "len()" used to summarize data. 📌 Key Takeaway: Python provides many powerful tools that allow us to write cleaner and more efficient code, which is very helpful when handling large datasets in AI and Machine Learning. Step by step, continuing my AI learning journey. #Python #ArtificialIntelligence #MachineLearning #DataScience #LearningInPublic #AIJourney
To view or add a comment, sign in
-
-
🔥 Day 11 — The 30-Day AI & Analytics Sprint with Instant Software Solutions A small line of Python… A big lesson about memory. matrix = [[1, 2, 3]] * 3 flat = [num for row in matrix for num in row] Looks clean, right? But here’s what’s really happening 👇 🧠 The Hidden Problem matrix = [[1, 2, 3]] * 3 This does NOT create three separate lists. Python creates one inner list, then repeats the reference to it three times. All rows point to the same memory address. So if you run: matrix[0][0] = 99 The entire matrix becomes: [[99, 2, 3], [99, 2, 3], [99, 2, 3]] Because you didn’t copy the list… You copied the reference. ✅ Why Flattening Still Works flat = [num for row in matrix for num in row] This nested list comprehension: • Loops through each row • Then loops through each number • Builds a brand new list Output: [1, 2, 3, 1, 2, 3, 1, 2, 3] It works because we’re reading values — not modifying them. 💡 The Correct Way If you want independent rows: matrix = [[1, 2, 3] for _ in range(3)] Now each row has its own memory space. 🎯 Lesson of the Day Multiplying nested lists duplicates references — not objects. Understanding this detail is what separates writing code that works… from writing code that scales safely. #100DaysOfCode #AISprint #MachineLearning #DataScience #Programming #SoftwareEngineering #BackendDevelopment #The_30_Day_AI_&_Analytics_Sprint #Python #AI #DataAnalysis #LearningJourney 🚀
To view or add a comment, sign in
-
-
Checkout my latest blog where I show you how you can write a python function with no implementation that still gets the job done. You write a docstring, a return type, and validation logic. The python function implements itself… with the help of an AI agent 👀 In this post, I explore AI Functions, a new experimental library from Strands Labs that flips how you write AI-powered code. Instead of calling a model, parsing the response, and writing retry logic, you declare what the function should do in the docstring and define what correct means through post-conditions. The AI handles the implementation. You write the post-conditions that validate the output. If validation fails, the error feeds back to the model and it tries again. I built a receipt parser with it. The model extracts line items from messy receipt text, and a post-condition verifies that the math adds up. Wrote up the full walkthrough with a working code example 🔗 : https://lnkd.in/eAt4cq8f #ai #aiagents #aws
To view or add a comment, sign in
-
-
LLMs aren't magic. They're just 200 lines of Python. Andrej Karpathy just dropped microGPT, the "final boss" of his educational projects. It’s a complete GPT-2 implementation in 200 lines with zero dependencies. But how do you actually use it? Karpathy demonstrates its power by training it on a dataset of 32,000 names. By the end of the script, the model "hallucinates" brand-new, plausible names (like vialan or konna) by learning the statistical patterns of the alphabet. You can use microGPT to: 1. Learn the "Gears": Step through the Value class to see exactly how backpropagation calculates gradients. 2. Train on your own "Mini-Documents": Swap out the names for any small text dataset (like Pokémon names or CSS colors) and watch it learn to generate them. 3. Experiment with the KV Cache: See exactly how "token communication" works in the attention block without the bloat of PyTorch. As Karpathy says: "Everything else is just efficiency." Read the full guide: https://lnkd.in/dPaguY39 "What's the most complex thing you've ever seen simplified to its bare essentials?" Answer in comments. #AI #MachineLearning #Python #AndrejKarpathy #Education #LLM
To view or add a comment, sign in
-
-
Day 18 – The 30-Day AI & Analytics Sprint 🐍 Python Discussion When working with lists in Python, there are two common ways to sort data: lst1.sort() and sorted(lst1) At first glance they may look similar… but they behave differently. 1️⃣ lst1.sort() Sorts the original list in place It modifies the existing list Does not return a new list Example: lst1 = [5, 2, 8, 1] lst1.sort() print(lst1) Output: [1, 2, 5, 8] Here the original list itself is changed. 2️⃣ sorted(lst1) Returns a new sorted list The original list remains unchanged Example: lst1 = [5, 2, 8, 1] new_list = sorted(lst1) print(new_list) print(lst1) Output: [1, 2, 5, 8] [5, 2, 8, 1] 📌 When should we use each one? Use .sort() when: You want to modify the original list Performance and memory efficiency matter Use sorted() when: You want to keep the original data unchanged You need a new sorted version of the list 💡 Key takeaway .sort() → modifies the list sorted() → returns a new sorted list Curious to know: Which one do you usually prefer when working with data? 🤔 #Python #DataAnalytics #AI #LearningInPublic #30DaysChallenge #PythonTips
To view or add a comment, sign in
-
🚀 Python Brain Teaser – Can you predict the output? During our AI & Data Analytics Sprint, we had this interesting question: Python Copy code d = {True: 'yes', 1: 'no', 1.0: 'maybe'} print(d) 🤔 What do you think the output will be? Most developers expect: Copy code {True: 'yes', 1: 'no', 1.0: 'maybe'} But the real output is: Copy code {True: 'maybe'} 🔥 Why? Because in Python: True == 1 → ✅ 1 == 1.0 → ✅ All three have the same hash value Dictionary keys must be unique So Python treats True, 1, and 1.0 as the same key. And since dictionaries keep the last assigned value, the final result becomes: Python Copy code {True: 'maybe'} 💡 Lesson learned: Understanding how Python handles equality and hashing is crucial — especially when working with data structures in AI, analytics, and backend systems. Subtle behaviors like this can cause silent logical bugs in real-world projects. 👇 Did you get it right before reading the explanation? #Python #AI #DataAnalytics #Coding #LearningEveryday #TechMindset
To view or add a comment, sign in
-
LEVIATHAN: A New Frontier in Agent-Based Social Evolution https://lnkd.in/dgxDZHe9 Unlock the Power of AI with Simple Python Requests! Harness the capabilities of AI with our user-friendly guide. Dive into a straightforward approach for integrating agents into your applications using Python. Here’s how you can get started: Step 1: Register Your Agent. Send a POST request to register your agent. Step 2: Retrieve Your API Key. Securely access your personalized API key for authentication. Step 3: Execute Actions. Use your key to perform actions in the AI world seamlessly. Key Takeaways: Efficiency in AI integration. User-friendly Python examples. Enhance your tech projects effortlessly! Whether you’re a seasoned AI enthusiast or just starting out, this guide is designed with your needs in mind. 🔗 Ready to revolutionize your projects? Explore the full guide now! Share your insights below and let's connect over innovation! #ArtificialIntelligence #Python #TechTrends Source link https://lnkd.in/dgxDZHe9
To view or add a comment, sign in
-
-
Starting my journey into AI & Machine Learning I completed my first data analysis project using Python. In this project, I built a script that: ✅ Loads a CSV dataset ✅ Calculates Mean, Median, Mode and Standard Deviation ✅ Visualizes data distribution using a histogram This experience helped me understand an important lesson — before building Machine Learning models, understanding data statistically is essential. Tools & Technologies: • Python • Pandas • NumPy • Matplotlib • Git & GitHub Through this project, I learned how data analysis forms the foundation of AI systems. 🔗 Project available on GitHub: https://lnkd.in/g_-ZPRdb Next step is deeper exploration into data preprocessing and machine learning concepts. #Python #DataScience #MachineLearning #AI #LearningJourney #GitHub #BeginnerToEngineer
To view or add a comment, sign in
-
-
🚀 Day 19 – The 30-Day AI & Analytics Sprint 🐍 Python Challenge What will be the output of this code? x = 0 for i in range(5): try: if i == 1: raise ValueError if i == 3: continue if i == 4: break x += i except ValueError: x += 10 print(x) Options: A) 10 B) 11 C) 12 D) 14 💡 Let's break it down The loop runs through: 0, 1, 2, 3, 4 When i = 1 → a ValueError is raised → handled by except → x += 10 When i = 3 → continue skips the rest of the loop When i = 4 → break stops the loop completely After tracing the execution step by step: ✅ Final value of x = 12 🎯 Key Learning This example shows how different control flow tools interact together: try / except raise continue break Understanding how these work inside loops is very important when writing robust Python code. 💬 Curious to know: Did you get the correct answer on the first try? #Python #AI #DataAnalytics #LearningInPublic #30DaysChallenge #PythonTips
To view or add a comment, sign in
Explore related topics
- How to Improve Memory Management in AI
- LeetCode Array Problem Solving Techniques
- How to Overcome AI-Driven Coding Challenges
- Understanding Dynamic Memory Systems in AI
- The Role of Memory in Artificial Intelligence
- How to Build AI Agents With Memory
- How to Optimize Machine Learning Performance
- Challenges and Benefits of Deep Learning in AI
- Best Practices for Memory Management in AI Conversations
- How to Use Memory Innovation in AI Hardware
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