Tried solving a sliding window problem today in Python Found the maximum average subarray of size k without recalculating everything again and again — just shifting the window and updating the sum. Simple logic, but really powerful for optimization! nums = [1,12,-5,-6,50,3] n = len(nums) k = 4 max_avrg = float("-inf") window = sum(nums[:k]) max_avrg = window/k for j in range (k,n): window = window - nums[j-k] + nums[j] if max_avrg < window/k: max_avrg = window/k print(max_avrg) Learning DSA step by step #Python #DSA #SlidingWindow
Max Average Subarray of Size K in Python
More Relevant Posts
-
Simple way to understand vector search in RAG I made a small Python example using SentenceTransformers + FAISS to understand how retrieval works in RAG. What happens here: A few documents are converted into embeddings Those embeddings are stored in FAISS A user question is also converted into an embedding FAISS finds the most similar document chunks This is the basic idea behind RAG: store meaning as vectors, then retrieve the most relevant context before generation Very small code, but it explains a very important concept. Text → Embedding → Similarity Search → Relevant Chunks That is why vector databases are so important in RAG systems. #RAG #FAISS #Embeddings #AIEngineering #Python #LLM Code source: https://lnkd.in/g-cm4BB2
To view or add a comment, sign in
-
-
Finding Maximum Sum of k Consecutive Elements in Python Check out this simple sliding window trick to get the maximum sum of k consecutive numbers in an array. I used my own code to solve it: Python Copy code nums = [7,1,5,1,3,2] k = 3 n = len(nums) window = sum(nums[:k]) sums = window for i in range(k,n): window = window - nums[i-k] + nums[i] if sums < window: sums = window print(sums) How it works: Start with the sum of the first k numbers Slide the window by removing the first number and adding the next Keep track of the maximum sum Fast, simple, and efficient! #Python #DSA #Coding #Algorithms #LearnByDoing #DeveloperLife
To view or add a comment, sign in
-
🐍 Day 22 of My 30-Day Python Learning Challenge Today I improved my Log File Analyzer by allowing user input (file name) instead of hardcoding. 📌 Code: filename = input("Enter file name: ") with open(filename, "r") as file: content = file.read().lower() print(content[:100]) # preview first 100 characters 📌 Why this matters? • Makes the program flexible • Works with any file • Closer to real-world usage 📊 Quick Question What happens if the user enters a wrong file name? A) Program crashes B) Empty output C) None D) Skips execution Answer tomorrow 👇 #Python #MiniProject #UserInput #LearningInPublic #SoftwareDeveloper
To view or add a comment, sign in
-
🚀 Day 2 of #100DaysOfCode Today I learned how to check whether a number is a Palindrome using Python 🐍 🔍 Problem: A number is called a palindrome if it reads the same forward and backward (like 121, 1331). 💡 Approach: Reverse the number using a loop Compare it with the original number 🐍 Code: num = int(input("Enter a number: ")) original = num reverse = 0 while num > 0: digit = num % 10 reverse = reverse * 10 + digit num = num // 10 if original == reverse: print("Palindrome Number") else: print("Not a Palindrome Number") 📌 Key Learning: Learned how loops and basic logic can solve interesting problems. 💬 Next: Armstrong Number 🔥 #Python #Coding #100DaysOfCode #Learning #CSE
To view or add a comment, sign in
-
-
Day 4 of learning Python Today I learned about TUPLES: Used to store multiple items in one variable Ordered & allow duplicate values Immutable (cannot change, add, or remove items) Key Concepts: Access items using indexing (positive & negative) Find length using len() Check item using "in" keyword Loop through tuple using for loop Important: To create a single item tuple → use comma Example: ("apple",) Workaround for updating tuple: Tuple → List → Modify → Convert back to Tuple Adding items: Tuples don’t support append(), but we can: Convert to list OR Add another tuple Practiced: Indexing Looping Checking elements Updating using workaround #Python #CodingJourney #100DaysOfCode #WomenInTech #LearnToCode
To view or add a comment, sign in
-
Most implementations of the State pattern in Python look very “clean”. Lots of small classes. A base interface. One class per state. But if you’ve ever worked with one in a real project, you know the downside: transitions are scattered, behaviour is hard to see in one place, and adding new states often means touching multiple files. In today’s video, I rebuild the State pattern in a very different way. Instead of relying on inheritance, I make the state machine explicit as data and use decorators to define transitions. The result is a small, reusable engine where the entire flow becomes visible at a glance. If you’re interested in writing Python that’s easier to reason about and extend, this is a pattern worth understanding. 👉 Watch here: https://lnkd.in/e9Y3xGNF. #python #softwaredesign #designpatterns #statemachine #cleancode
To view or add a comment, sign in
-
-
Most implementations of the State pattern in Python look very “clean”. Lots of small classes. A base interface. One class per state. But if you’ve ever worked with one in a real project, you know the downside: transitions are scattered, behaviour is hard to see in one place, and adding new states often means touching multiple files. In today’s video, I rebuild the State pattern in a very different way. Instead of relying on inheritance, I make the state machine explicit as data and use decorators to define transitions. The result is a small, reusable engine where the entire flow becomes visible at a glance. If you’re interested in writing Python that’s easier to reason about and extend, this is a pattern worth understanding. 👉 Watch here: https://lnkd.in/eg22yEHR. #python #softwaredesign #designpatterns #statemachine #cleancode
To view or add a comment, sign in
-
-
🐍 Python Tip 4: Difference between append() and extend() Many learners get confused between these two list methods. append() Adds the entire object as one element: numbers = [1, 2, 3] numbers.append([4, 5]) print(numbers) Output: [1, 2, 3, [4, 5]] extend() Adds each element individually to the list: numbers = [1, 2, 3] numbers.extend([4, 5]) print(numbers) Output: [1, 2, 3, 4, 5] 💡 Key difference: • append() → adds as a single item • extend() → adds multiple items separately Why this matters? Understanding this helps avoid unexpected list structures, especially while working with datasets or loops. Small concept — but very useful in practice! #Python #PythonTips #Programming #LearnPython #DataScience #CodingTips
To view or add a comment, sign in
-
Day 7 of my Python learning journey: Today I focused on classic array and string patterns, and tried to keep solutions clean and efficient. What I solved: Two Sum using brute-force and hash map Valid Palindrome with two pointers Move Zeros with an in-place two-pointer approach Container With Most Water in O(n) Big takeaway: Correctness first, clarity second, optimization third. Small design choices, like in-place updates vs extra arrays, really affect code quality. GitHub link: https://lnkd.in/gGPw8_js #Python #ProblemSolving #Algorithms #TwoPointers #LearningInPublic #CleanCode
To view or add a comment, sign in
-
Day 22/100 – #100DaysOfCode 🚀 Solved LeetCode #560 – Subarray Sum Equals K (Python). Today I learned how prefix sum and hashmap can be used together to efficiently count subarrays with a given sum. Approach: 1) Initialize count = 0 and curr_sum = 0. 2) Use a hashmap to store prefix sum frequencies (start with {0:1}). 3) Traverse the array and keep adding elements to curr_sum. 4) Check if (curr_sum - k) exists in the hashmap. 5) If it exists, add its frequency to count. 6) Update the hashmap with the current prefix sum. Time Complexity: O(n) Space Complexity: O(n) Understanding prefix sum + hashmap pattern is a game changer 💪 #LeetCode #Python #DSA #HashMap #PrefixSum #ProblemSolving #100DaysOfCode
To view or add a comment, sign in
-
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