Day 5 of my #100DaysOfCode challenge 🚀 Today I worked on a Python program to rotate a list by k positions. List rotation means shifting elements so that items moved out from the front reappear at the end of the list. What the program does: • Takes a list and a value k from the user • Handles edge cases like an empty list • Uses modulo (k % length) to avoid unnecessary rotations • Rotates the list efficiently using slicing How the logic works: 1) If the list is empty, it is returned as-is 2)The value of k is adjusted using modulo to handle cases where k is larger than the list size 3)The list is split into two parts: – Elements from index k to the end – Elements from the start to index k 4)Both parts are joined to form the rotated list Example 1: Original list: [1, 2, 3, 4, 5] k = 2 Output: [3, 4, 5, 1, 2] Example 2: Original list: [1, 2, 3, 4, 5] k = 4 Output: [5, 1, 2, 3, 4] Key learnings from Day 5: – List slicing in Python – Handling edge cases safely – Using modulo for optimized logic – Writing clean and reusable functions #Day5 #100DaysOfCode #PythonLists #ListManipulation #AlgorithmPractice #CodingDaily #PythonDeveloper #LearnByCoding
Rotating Lists with Python: Efficient List Rotation Logic
More Relevant Posts
-
🐍 Day 11 of my Python Full-Stack Journey — Tuples! Today I explored one of Python's most underrated data structures: Tuples 📦 At first glance, they look just like lists — but the key difference? They're immutable. Once created, you can't change them. Here's what I learned: ✅ Creating a tuple → my_tuple = (1, 2, 3) or even just 1, 2, 3 ✅ Accessing elements → Same indexing as lists: my_tuple[0] ✅ Tuple unpacking → a, b, c = (10, 20, 30) — super clean! ✅ Single element tuple → Don't forget the trailing comma: (5,) not (5) ✅ Tuples as dictionary keys → Unlike lists, tuples are hashable! Why use tuples over lists? → Faster performance → Protects data from accidental modification → Great for returning multiple values from a function python def get_user(): return ("Alice", 25, "Developer") name, age, role = get_user() Simple, clean, and Pythonic. 💡 Still going strong on this journey — Day 12 coming tomorrow! 🚀 #Python #FullStackDevelopment #100DaysOfCode #PythonLearning #CodingJourney #Day11 #Tuples #LearnToCode
To view or add a comment, sign in
-
-
✅ Create Virtual Environment Using Ctrl + Shift + P (VS Code) 🔹 Step 1: Open Your Project Folder in VS Code Make sure your project contains: Your Python files (Optional) requirements.txt 🔹 Step 2: Open Command Palette Press: Ctrl + Shift + P 🔹 Step 3: Type Python: Create Environment Click it ✅ 🔹 Step 4: Choose Environment Type You will see options like: Venv Conda Choose Venv. 🔹 Step 5: Choose Python Interpreter Select the Python version you want (for example Python 3.10). VS Code will: ✔ Create .venv folder ✔ Automatically activate it ✔ Select interpreter 📦 Install From requirements.txt Automatically If your project has requirements.txt, VS Code will usually detect it and ask: “Install dependencies from requirements.txt?” Click Yes ✅ It will install all packages for you.
To view or add a comment, sign in
-
Day 9: Flow Control — Giving Your Code a Brain 🧠 The Flow Control, and in Python, it relies on one golden rule: Indentation. 1. The Rule of the Space: Indentation In other languages, you might use curly braces {} to group code. In Python, we use Whitespace. The Concept: A block of code starts with an indentation (usually 4 spaces) and ends when the indentation stops. 💡 The Engineering Lens: Indentation isn't just for "looks"—it's functional. If your alignment is off by even one space, your program will either crash or run the wrong logic. Consistency is non-negotiable in professional code. 2. The "If" Statement: The First Gate The if statement checks a condition. If it's True, the code inside the block runs. Example: if user_age >= 18: print("Access Granted") 3. The "Else" Statement: The Safety Net What happens if the `if` condition is `False`? The `else` block catches everything else. The Concept: It doesn't need a condition of its own. It is the "default" path. 💡 The Engineering Lens: Always think about the "Negative Path." What should the system do if things don't go as planned? 4. The "Elif" Statement: Multiple Paths Short for "Else If," `elif` allows you to check multiple specific conditions in order. The Process: Python checks the `if` first. If that fails, it checks the first `elif`. If that fails, it checks the next, and so on. ⚠️ Important: Once Python finds a condition that is `True`, it runs that block and skips the rest of the chain. 5. The "Senior" Way: Guard Clauses ❌ The Rookie Way: Nesting `if` inside `if` inside `if` (creating a "Pyramid of Doom"). ✅ The Pro Standard: Use a "Guard Clause." Check for the error/invalid case first and exit early. Example: if not is_logged_in: return "Please log in" # Rest of the code stays "flat" and readable #Python #SoftwareEngineering #CleanCode #ProgrammingBasics #LearnToCode #CodingTips #TechCommunity #PythonDev
To view or add a comment, sign in
-
Day 15/100: My code finally talked back! 🎙️✨ For two weeks, I’ve been talking at my computer. Today, it started listening. I mastered the input() function! The Catch: Python is a bit of a literalist. If you tell it you’re 25, it thinks you’re the word "25," not the number. Without Type Casting (int()), your math becomes a mess. It's the difference between "25 + 1 = 26" and "25 + 1 = 251." 🤦♂️ The Code: Python name = input("Enter your name: ") age = int(input("Enter your age: ")) # Casting to int so Python doesn't get confused print(f"Hi {name}! {age} is a great age to master Python. 🚀") Moving from static scripts to interactive tools feels like a massive level-up. ⬆️ #100DaysOfCode #Python #InteractiveCode #CodingLife #LearnToCode
To view or add a comment, sign in
-
-
🧠 Python Concept That Explains Class Creation Order: Class Body Execution In Python, a class body is executed like normal code 👀 🤔 The Surprise class Demo: print("Inside class") ✅ Output Inside class Wait… no object created 🤯 But code ran. 🧠 What Actually Happens When Python sees: class Demo: x = 10 It does roughly: 1️⃣ Create namespace dict 2️⃣ Execute class body 3️⃣ Store names in namespace 4️⃣ Build class object 🧪 Proof class Demo: x = 10 y = x + 5 print(Demo.y) # 15 y computed during class creation 🎯 🧒 Simple Explanation 🧸 Imagine building a toy 🧸 Before selling it: 💫 workers assemble parts inside factory. 💫 That assembly = class body execution. 💡 Why This Matters ✔ Metaclasses ✔ Descriptors ✔ Decorators ✔ ORMs ✔ Framework internals ⚡ Fun Fact List comprehensions inside class have their own scope 👀 🐍 In Python, a class isn’t just declared. 🐍 Its body actually runs 🐍 Classes are built by executing code first. #Python #PythonTips #PythonTricks #AdvancedPython #CleanCode #LearnPython #Programming #DeveloperLife #DailyCoding #100DaysOfCode
To view or add a comment, sign in
-
-
Day 17 of my #100DaysOfCode challenge 🚀 Today I worked on a Python program to count the number of vowels and consonants in a given string. The goal was to practice string traversal and character classification. What the program does: • Takes a string input from the user • Converts the string to lowercase for consistency • Checks each character individually • Counts vowels and consonants separately • Returns both counts How the logic works: A function count_vowels_consonants(string) is defined Two strings are created: – One containing all vowels (aeiou) – One containing all consonants Two counters are initialized to 0 The program loops through each character in the string If the character is in the vowel string, vowel count increases If the character is in the consonant string, consonant count increases The function returns both counts Example: Input: my name is SATISH KUMAR Output: Vowels: 7 Consonants: 12 Key learnings from Day 17: – Iterating through strings – Using conditional statements effectively – Handling case sensitivity with .lower() – Strengthening basic string manipulation skills #100DaysOfCode #Day17 #Python #PythonProgramming #StringManipulation #ProblemSolving #CodingPractice #LogicBuilding #LearnByDoing #ComputerScience #BTech #CSE #AIandML #VITBhopal #TechJourney
To view or add a comment, sign in
-
-
Day 14 – Exploring Built-in Functions & Python Standard Libraries Day 14 was focused on understanding how Python makes our work easier through built-in functions and standard libraries. Instead of writing everything from scratch, I explored how to use ready-made tools effectively and correctly. What I learned and practiced today: Built-in Functions: Used pow(), sum(), max(), and min() for basic computations Practiced rounding values using round() with positive and negative precision Understood how these functions accept parameters and return results Math Module (math): Calculated factorials and square roots Worked with constants like pi and e Used trigonometric functions such as sin() (with radians) Explored mathematical helpers: ceil(), floor(), trunc() fabs() for absolute values log() and log10() for logarithmic calculations Random Module (random): Generated random numbers using: random() for floats randint() for integers uniform() for float ranges Selected random elements using choice() and sample() Shuffled lists using shuffle() and observed in-place modification behavior Collections Module (Counter): Used Counter to count occurrences of elements in a list Learned how it efficiently tracks frequency of unique values Key Takeaways: Python’s standard libraries save time and reduce code complexity Understanding return values and in-place operations is important Libraries are powerful only when used with proper understanding Every day, I’m getting more comfortable with Python’s ecosystem and learning how to write cleaner and smarter code. Hashtags #Python #PythonLibraries #BuiltInFunctions #MathModule #RandomModule #Collections #Counter #DailyLearning #ProgrammingBasics #CodingJourney
To view or add a comment, sign in
-
🚀 Day 41 –#100DaysOfCode LeetCode 696: Count Binary Substrings Today I solved LeetCode 696 – Count Binary Substrings. 🧩 Problem Summary Given a binary string, count the number of non-empty substrings that: Have equal number of 0s and 1s All 0s are grouped together All 1s are grouped together 💡 Key Insight Instead of checking all substrings (which would be inefficient), we: 1️⃣ Count lengths of consecutive groups 2️⃣ Add min(previous_group, current_group) for each adjacent pair That’s it! 🎯 ✅ Optimized Approach (O(n) time | O(1) space) Copy code Python class Solution: def countBinarySubstrings(self, s: str) -> int: prev_group = 0 curr_group = 1 result = 0 for i in range(1, len(s)): if s[i] == s[i-1]: curr_group += 1 else: result += min(prev_group, curr_group) prev_group = curr_group curr_group = 1 result += min(prev_group, curr_group) return result 🧠 What I Learned Pattern recognition is powerful Instead of brute force, think in terms of groups Many string problems reduce to counting consecutive elements Consistency > Motivation 💪 #Day41 #LeetCode #DSA #ProblemSolving #CodingJourney #Python #100DaysOfCode
To view or add a comment, sign in
-
-
Passing tests isn’t the same as understanding the code! 😐 When I first started solving Python tasks, I focused on one thing: make the tests pass. And if they passed — I moved on. 🏃♂️➡️ Lately I’ve been doing something different... 💭 After the solution works, I pause and ask: Can this be simpler? Is it readable? Would I understand it in a month? That second step changes everything. Refactoring feels slower. But it builds clarity. I’m starting to realize that growth doesn’t happen when the code works. It happens when you improve it. < Small shift. > Big difference. What do you usually do after your solution works — move on, or refine it? 👇 #MateAcademy #LearningJourney #DeveloperJourney #PythonLearning #Git #BecomingADeveloper #Python
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