“Python(Basic) Questions from a HackerRank Assessment I Recently Cleared" 🔹 Problem Statement You are given a sentence consisting of space-separated words with upper and lower case English letters. Each word must be transformed using the following rules: The first character of each word remains unchanged For every next character: Compare it with the previous character (case-insensitive) If the previous character comes earlier in the alphabet → convert current character to uppercase If the previous character comes later → convert current character to lowercase If both characters are the same → keep it unchanged Spaces should remain as they are 🔹 Logic / Approach Traverse the sentence character by character Reset comparison whenever a space is encountered Keep track of the previous character Compare characters using lower() to avoid case issues Apply transformation rules and build the result step by step This ensures accurate transformation while preserving word boundaries. 🔹 Code Implementation (Python) def transformSentence(sentence): result = [] prev_char = None for ch in sentence: if ch == " ": result.append(" ") prev_char = None else: if prev_char is None: result.append(ch) else: if prev_char.lower() < ch.lower(): result.append(ch.upper()) elif ch.lower() < prev_char.lower(): result.append(ch.lower()) else: result.append(ch) prev_char = ch return "".join(result) 🔹 Sample Input a Blue MOON 🔹 Output a BLUe MOOn #Python #HackerRank #CodingPractice #ProblemSolving #LearningJourney #SoftwareEngineering
Python HackerRank Sentence Transformation Challenge
More Relevant Posts
-
In plain English, "and" and "or" are just connective words. In Python, they are strict gatekeepers. 🧐 ⠀ Confusing them is the easiest way to break the logic of your application. ⠀ Let's look at a real-world example: Going to the cinema. 🍿 ⠀ 🎬 The "Flexible" Approach (OR): Imagine regular entry to a movie. You write: `if has_paper_ticket OR has_digital_app:` ⠀ The `or` operator is chill. It opens the door if *either* condition is met. Did you forget your paper ticket but have your phone? No problem. You're in. ⠀ 🔞 The "Strict" Approach (AND): Now imagine entry to an age-restricted screening (18+). You write: `if has_ticket AND is_over_18:` ⠀ The `and` operator is the strict manager. It demands *both* requirements be met simultaneously. Have a ticket but forgot your ID? You aren't getting in. ⠀ Logical operators aren't just syntax; they define the rules of your digital world. ⠀ Don't accidentally lock your users out (or let the wrong ones in) because you chose the wrong conjunction. ⠀ We turn boring Python documentation into a friendly, 3-minute daily habit. ☕ ⠀ 👇 Subscribe to the website for free: https://lnkd.in/ducXvs-y ⠀ #Python #Logic #CodingTips #SoftwareDevelopment #LearnToCode #PyDaily
To view or add a comment, sign in
-
-
Python weirdness — 500 "None" values but only ONE object in memory I ran a small experiment today. I created a list: lst = [None for _ in range(500)] len(lst) Output: 500 So Python created 500 "None" objects… right? No. Now check this: all(x is None for x in lst) Output: True Every element is the SAME "None". Let’s inspect memory: len({id(x) for x in lst}) Output: 1 Only ONE memory address Python does NOT create new "None" objects. There is exactly one "None" in the entire interpreter. Whenever you write: x = None you are just referencing a pre-existing object. This is why Python developers always write: if value is None: and not: if value == None: Because "is" checks identity, and "None" has a guaranteed single identity (a language-level singleton). Other singleton objects in Python: • True • False • NotImplemented • Ellipsis (...) Takeaway: Python isn’t just a scripting language. It’s a carefully designed object system. Sometimes a tiny keyword like "None" teaches more about memory than a whole textbook. #Python #Programming #SoftwareEngineering #CodingTips #BackendDevelopment
To view or add a comment, sign in
-
🐍 Python felt slow… until I stopped blaming Python. I had an API that worked fine in dev. Same code. Same logic. But in production? Latency spikes. Random slowness. No clear pattern. After digging deep, I found the real culprit 👇 🧠 Python wasn’t slow. Blocking I/O was. One tiny line was doing this: • Waiting for a network call • Blocking the entire worker • Holding resources idle Everything else waited. 💡 The turning point: I stopped asking “Is Python fast?” I started asking: ❓ Is this I/O-bound or CPU-bound? Once I: ✔ Used async for I/O ✔ Offloaded CPU-heavy work ✔ Stopped blocking the event loop Performance improved. Without changing languages 😌 ✨ Real backend lesson: • Python is great at I/O • Python is bad at pretending to be multi-core • Design decisions matter more than syntax Languages don’t fail systems. Architectures do. If Python ever felt slow to you, this might be why. #Python #BackendDevelopment #AsyncProgramming #SoftwareEngineering #Performance #DeveloperLearning
To view or add a comment, sign in
-
-
Quick check: what’s the type of bin(10)? int? float? Something else? It’s str. bin(), oct(), and hex() always return strings. That’s why bin(10) + 5 fails and why you use int(bin(10), 2) when you need a number again. I wrote a complete guide to Python base conversion functions so you can: ✓ Use bin(), oct(), and hex() correctly ✓ Know they return strings (and convert back when needed) ✓ Avoid float/complex (only int and bool work) ✓ Fix the usual mistakes and read the common errors ✓ See practical use (e.g. colors, permissions) and try exercises ~23 min read, with examples and solutions. Link: https://lnkd.in/dnUxjXBB #Python #LearnPython #Programming #Tech
To view or add a comment, sign in
-
A small Python bug that taught me a big lesson about mutability 🐍 Today’s debugging session turned into a surprisingly valuable learning moment. I was working on a function where I needed to update a list by adding a few extra values. The logic looked straightforward, everything was running fine, and there were no errors. So I assumed the task was done ✅ But later, I noticed something strange 👀 A piece of data that I never intended to modify was changing on its own. No exceptions. No warnings. Just incorrect output ❌ After adding logs, stepping through the code, and debugging carefully, the real issue became clear 💡 👉 The problem wasn’t my logic — it was Python’s behavior. In Python, lists are mutable. When you assign a list to another variable, both variables point to the same object in memory. Any in-place operation (`extend`, `append`, etc.) affects all references to that list. A simplified example: original_data = {"values": [1, 2, 3]} working_list = original_data["values"] working_list.extend([4, 5]) Expected: [1, 2, 3] Actual: [1, 2, 3, 4, 5] 😅 The fix was simple but powerful 🛠️ Create a copy before modifying the data: working_list = original_data["values"].copy() working_list.extend([4, 5]) ✔️ No side effects ✔️ Predictable behavior ✔️ Bug resolved Key takeaway ✨ 🔹 Mutability is powerful, but it can introduce silent bugs 🔹 Bugs without errors are often the hardest to detect 🔹 Be intentional when working with shared data structures Just because code works doesn’t always mean it’s correct. Debugging is where real learning happens 🚀 #Python #Debugging #BackendDevelopment #SoftwareEngineering #CodingLife #ProgrammingTips #CleanCode #LearningByDoing #DeveloperJourney #ProblemSolving
To view or add a comment, sign in
-
Exploring Python Context Managers under the hood Context managers are one of Python's most powerful features for resource management. I’ve been diving into how the context protocol works, and it’s fascinating to see how the with statement actually operates. To implement a context manager from scratch, you need two dunder methods: __enter__: Sets up the environment. If you’re opening a file or a database connection, this method prepares the object and returns it. __exit__: Handles the cleanup. It ensures that regardless of whether the code succeeds or crashes, the resources (like file handles or network sockets) are properly closed. As a fun experiment, I wrote this helper class to redirect print statements to a log file instead of the console: import sys class MockPrint: def __enter__(self): # Store the original write method to restore it later self.old_write = sys.stdout.write self.file = open('log.txt', 'a', encoding='utf-8') # Redirect stdout.write to our file logic sys.stdout.write = self.file.write return self def __exit__(self, exc_type, exc_value, traceback): # Restore the original functionality and close the file sys.stdout.write = self.old_write self.file.close() # Usage with MockPrint(): print("This goes to log.txt instead of the console!") While Python’s standard library has tools like contextlib.redirect_stdout for this exact purpose, building it manually really helped me understand how the protocol manages state and teardown. It’s a simple concept, but it's exactly what makes Python code so clean and safe. #Python #SoftwareEngineering #Backend
To view or add a comment, sign in
-
🚀 Stop Writing "Slow" Python: The Architect's Performance Playbook Most developers treat Python like a black box. The Top 1% treat it like a high-performance engine. If your production code is crawling, you aren't hitting the limits of the language—you’re hitting the limits of your architecture. Here are 4 shifts to move from Script Kiddy to Systems Architect: 1. 🧠 Memory Layout Matters (Slots vs. Dicts) Python’s __dict__ is flexible but heavy. When scaling to millions of objects, the memory overhead is lethal. Use __slots__ to freeze the attributes and drastically reduce the memory footprint. Impact: 40-50% reduction in memory usage. When: Large-scale data processing or long-lived microservices. 2. ⚡ The Global Interpreter Lock (GIL) is Changing With PEP 703 (No-GIL) and sub-interpreters (PEP 684), the game has changed. Stop relying solely on multiprocessing for CPU-bound tasks. The Pro Move: Explore interpreters in Python 3.12+ to run truly parallel code without the massive overhead of separate OS processes. 3. 🏎️ Vectorization > Loops If I see a for loop over a dataset, we need to talk. Python is slow; C is fast. Use NumPy or Pandas to push your calculations down to the C-layer. The Secret: Vectorized operations use SIMD (Single Instruction, Multiple Data) at the CPU level. 4. 🛠️ Profiling: Don't Guess, Measure Stop "optimizing" by feeling. Use the right tools: Py-spy: A sampling profiler that lets you see where your production code is stuck without restarting it. Scalene: A high-performance CPU, GPU, and memory profiler. 💡 The Architect's Verdict Performance isn't about writing "clever" code; it’s about understanding the C-Python runtime and the hardware beneath it. 👇 Let’s discuss in the comments! #Python #SoftwareArchitecture #Coding #PerformanceOptimization #BackendDevelopment #PythonTips
To view or add a comment, sign in
-
P̳a̳r̳t̳ ̳1̳.̳1̳ To discuss the key points of 𝐜𝐡𝐚𝐩𝐭𝐞𝐫 𝐨𝐧𝐞 from "𝑴𝒂𝒔𝒕𝒆𝒓𝒊𝒏𝒈 𝑴𝒂𝒄𝒉𝒊𝒏𝒆 𝑳𝒆𝒂𝒓𝒏𝒊𝒏𝒈 𝑷𝒚𝒕𝒉𝒐𝒏 𝒊𝒏 𝑺𝒊𝒙 𝑺𝒕𝒆𝒑𝒔" book (What have I got important from chapter one): 1) 𝐊𝐞𝐲𝐰𝐨𝐫𝐝𝐬: All the keywords are in lowercase except 𝐓𝐫𝐮𝐞, 𝐅𝐚𝐥𝐬𝐞, 𝐚𝐧𝐝 𝐍𝐨𝐧𝐞. 2) 𝐈𝐧𝐝𝐞𝐧𝐭𝐚𝐭𝐢𝐨𝐧: Indentation is required to indicate which block of code a code or statement belongs to. Incorrect indentation, program will generate a 𝐬𝐲𝐧𝐭𝐚𝐱 𝐞𝐫𝐫𝐨𝐫 3) 𝐒𝐮𝐢𝐭𝐞𝐬: A collection of individual statements that makes a single code block are called suites in Python. 4) • 𝐋𝐢𝐬𝐭: Use when you need an ordered sequence of homogenous collections, whose values can be changed later in the program. • 𝐓𝐮𝐩𝐥𝐞: Use when you need an ordered sequence of heterogeneous collections whose values need not be changed later in the program. • 𝐒𝐞𝐭: It is ideal for use when you don’t have to store duplicates and you are not concerned about the order or the items. You just want to know whether a particular value already exists or not. • 𝐃𝐢𝐜𝐭𝐢𝐨𝐧𝐚𝐫𝐲: It is ideal for use when you need to relate values with keys, in order to look them up efficiently using a key. 5) <> becomes True, if values of two operands are not equal. 𝐄𝐱𝐚𝐦𝐩𝐥𝐞- (x<>y) is true. This is similar to != operator. 6) 𝐌𝐞𝐦𝐛𝐞𝐫𝐬𝐡𝐢𝐩 𝐎𝐩𝐞𝐫𝐚𝐭𝐨𝐫𝐬: Membership operators are useful to test if a value is found in a sequence, that is, string, list, tuple, set, or dictionary. There are two membership operators in Python, ‘𝐢𝐧’ and ‘𝐧𝐨𝐭 𝐢𝐧’. 7) 𝐈𝐝𝐞𝐧𝐭𝐢𝐭𝐲 𝐎𝐩𝐞𝐫𝐚𝐭𝐨𝐫𝐬: Identity operators are useful to test if two variables are present on the same part of the memory. There are two identity operators in Python, ‘𝐢𝐬’ and ‘𝐢𝐬 𝐧𝐨𝐭’.
To view or add a comment, sign in
-
I built a very rudimentary AI agent with python last weekend in VS Code, and here’s what I learnt (no hype). Firstly: The only tools I gave the agent were “read_file” and “write_file”… when I say rudimentary, I really do mean it 😄 Takeaways: 1. An agent is fundamentally an LLM with the ability to discern tool use (a tool is python code or an api call to another platform), and decide when the task is complete (looping). 2. If you’re not a developer, building an agent outside of an orchestration platform isn’t a cake walk. I have a foundational understanding of python, but I wouldn’t have been able to write the code myself. I had to rely heavily on iteration and explanation with an LLM whilst building it out. 3. The development architecture of an agent is worth understanding. Files for tools, for the user prompt, for the agent itself, nestled within a project structure. And, lastly a perception: 4. After having done it, I’m now slightly more convinced that the number of people saying they’ve built an agent vs the actual number of agents built is probably quite exaggerated. But I’d be keen to learn how you’ve built an agent, what you did, and what the agent’s function was?
To view or add a comment, sign in
-
Ever wondered how Python knows what to do when you use + between two objects? Or how len() works on your custom class? The answer lies in magic methods (also called dunder methods). These are special methods wrapped in double underscores, and they're what make Python feel like magic. Here are a few that changed how I write code: __init__ — The constructor everyone knows. But it's just the beginning. __repr__ & __str__ — Control how your object looks when printed or logged. Debugging becomes 10x easier when your objects speak for themselves. __len__, __getitem__, __iter__ — Make your custom class behave like a built-in list or dictionary. Your teammates won't even know the difference. __enter__ & __exit__ — Power behind the with statement. Perfect for managing resources like files, DB connections, and locks. __eq__, __lt__, __gt__ — Define what "equal" or "greater than" means for your objects. Sorting a list of custom objects? No problem. __call__ — Make an instance callable like a function. This one unlocks some seriously clean design patterns. The real power of magic methods isn't just the syntax — it's that they let you write intuitive, Pythonic APIs that feel native to the language. When your custom class supports len(), iteration, and comparison naturally, your code becomes easier to read, test, and maintain. What's your favorite magic method? Drop it in the comments #Python #SoftwareEngineering #Programming #PythonTips #CleanCode #BackendDevelopment
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