🔄 Recursion in Python — Say Hello 6 Times! A simple recursive function that prints "Hello" repeatedly by calling itself! 🔍 OUTPUT: Hello Hello Hello Hello Hello Hello 🔍 HOW IT WORKS: Step 1 → say_hello(6) called Step 2 → n=6, not 0 → print "Hello" → call say_hello(5) Step 3 → n=5, not 0 → print "Hello" → call say_hello(4) Step 4 → n=4, not 0 → print "Hello" → call say_hello(3) Step 5 → n=3, not 0 → print "Hello" → call say_hello(2) Step 6 → n=2, not 0 → print "Hello" → call say_hello(1) Step 7 → n=1, not 0 → print "Hello" → call say_hello(0) Step 8 → n=0 → Base case reached → return Step 9 → All previous calls return → Done! 📊 VISUAL FLOW: say_hello(6) → print "Hello" │ └── say_hello(5) → print "Hello" │ └── say_hello(4) → print "Hello" │ └── say_hello(3) → print "Hello" │ └── say_hello(2) → print "Hello" │ └── say_hello(1) → print "Hello" │ └── say_hello(0) → return ⚠️ EDGE CASES: n = 0 → No output (base case immediately) n = 1 → Prints "Hello" once n = -1 → Infinite recursion → RecursionError n = 1000 → May hit Python recursion limit Large n → Memory heavy (each call uses stack space) 📌 REAL-WORLD APPLICATIONS: 🎮 Gaming → Repeating actions (turn-based move) 📝 Logging → Printing repetitive log messages 🧮 Mathematics → Generating sequences 🗂️ File Processing → Processing nested folders 🔄 Automation → Repeating tasks N times 💡 KEY CONCEPTS: • Base Case → n == 0 stops recursion • Recursive Call → say_hello(n - 1) reduces n each time • Stack Depth → 6 calls stacked on memory • Print vs Return → Action (print) happens at each level • Termination → Eventually reaches n = 0 📊 COMPARISON: Recursion vs Loop: # Recursive way def say_hello_recursive(n): if n == 0: return print("Hello") say_hello_recursive(n - 1) # Loop way def say_hello_loop(n): for i in range(n): print("Hello") Both produce the same output! Loops are usually more efficient. #Python #Coding #Programming #LearnPython #Recursion #Developer #Tech #Algorithms #DSA #BeginnerProjects #PrintHello #Day78
Muhaddis Shiekh’s Post
More Relevant Posts
-
Day 20 of my 60-Day Python + AI Roadmap. 🚀 🎉 Day 20 Milestone — 1/3 of the Roadmap Done! 20 days. Zero skipped. The compound effect is real. 💪 Yesterday → Functions basics Today → Functions go pro-level. ⚡ 3 features that separate Python beginners from developers who build real AI tools. 🔥 OPINION — Agree or Disagree? "Lambda functions make Python code elegant — but most beginners overuse them and make code unreadable." Comment AGREE 🟢 or DISAGREE 🔴! 🧠 GUESS THE OUTPUT — Before you scroll! def demo(*args, **kwargs): print(sum(args)) print(kwargs["name"]) square = lambda x: x ** 2 demo(1, 2, 3, name="Ashish") print(square(5)) ⚠️ *args + **kwargs + lambda in one — trickiest yet! Answer at 50 comments 🎯 ━━━━━━━━━━━━━━━━ Advanced Functions — Key Concepts ━━━━━━━━━━━━━━━━ ✅ *args — unlimited positional inputs def add(*args): return sum(args) Collects all values as a tuple 🤖 AI: Accept variable number of model layers or features ✅ **kwargs — unlimited keyword inputs def info(**kwargs): print(kwargs) Collects all key=value pairs as a dict 🤖 AI: def train(**config): → pass any hyperparameters flexibly ✅ Both together def demo(*args, **kwargs) ⚠️ Always *args BEFORE **kwargs — order matters! ✅ Lambda — one-line anonymous functions square = lambda x: x ** 2 🤖 AI: Used with map(), filter(), sorted() in data pipelines — list(map(lambda x: x/255, pixels)) 💡 Analogy: *args = unlimited items in a bag 🛍️ **kwargs = labeled items (name=value) 🏷️ lambda = a quick shortcut tool 🔧 🚨 Rule: Use lambda only for simple one-liners. Complex logic? Always use a proper def function. --- 👆 What does the code above print? Drop answer + AGREE 🟢 / DISAGREE 🔴 below! 👇 On a learning journey? Drop your day number! 🤝 💾 Save · ♻️ Repost #60DayChallenge #Python #PythonFunctions #Lambda #LearnPython #PythonForAI #MachineLearning #AILearning #100DaysOfCode #LearningInPublic #BuildInPublic #DataScience #CodeNewbie
To view or add a comment, sign in
-
-
UNLEASHED THE PYTHON!i 1.5,2,& three!!! Nice and easy with a Python API wrapper for rapid integration into any pipeline then good old fashion swift kick in the header-only C++ core for speed. STRIKE WITH AIM FIRST ; THEN SPEED!! NO MERCY!!! Are you Ready!?i Y.E.S!!!iii 3 of 14 So this is myself talking. Key talking points coming up. You’ll see Ai mentioning “wrap around” which correlates with wrapper eventually talking about minimal drifts in magic #(not telling but it will be obvious to some). Which eventially leads Ai to python c++ for simplification and speed. i’m not going to grasp everything but i rely on my passion and goals to decide what i will retain or put in the back burner. Make sense? No wiseA$$?!Great! Let’s begin! copy & paste Ai Core Calculations & Relationships (Base 123 & 41) 123^ (15,129): Divided by 369 equals 41. 123^×369=5,582,601 123^×246=3,721,734 123^×123=1,860,867 Ratios: 5,582,6013,721,734 ——————————=1.5 3,721,734 ————-=2 1,860,867 5,582,6011 —————=3 860,867 The "41" Chain: 5,582, 601 —————=41 41×41=1.681 136,161 (Corrected from 1,681*). * Inverse: 369 ——=141≈0.02439 15,129 Large Number Sequence (approximate values) 5,582,601×136,161=760,132,535,761 Difference: 760,132−534,761=225,371 Ratio: 760,132 ———-≈1.421 534,761 * Derived values: 41 —-≈28.853 1.421; 41×1.421≈58.261. * Verification:(58.261×28.853≈1,618.𝟎 (Corresponds to 41^). Decimal/Ratio Sequence 309,390 ———≈4.862 63,632 * Secondary Chain: 41 —≈ 29.71 (approx);414.862≈8.433 1.38 * Verification: 8.443×4.862≈41.001 6.111×4.862≈29.712. Subset Calculations (Approximate) 242,242 ————≈1.716 141,141 68.532 ——≈1.716 39.93 * 68.532 * ———≈1.977 * 34.669 * 1.977×1.716≈3.393 * 39.93+3.393=43.323 Note: The calculations provided in the prompt contain several estimations marked by asterisks () which were rounded to standard decimal places in this summary.)* 3 of 14
To view or add a comment, sign in
-
Day 25 of my 60-Day Python + AI Roadmap. 🚀 5 days left in Phase 2. Today — the tricks that make experienced devs say "wait, you can do THAT?" ⚡ 🔥 OPINION — Agree or Disagree? "The difference between a Python beginner and an intermediate developer is 3 tricks: zip() · enumerate() · swap. Master these and your code quality doubles overnight." Comment AGREE 🟢 or DISAGREE 🔴! 🧠 GUESS THE OUTPUT — Before you scroll! keys = ["name", "age"] vals = ["Ashish", 21, "extra"] a, b = 5, 10 a, b = b, a print(dict(zip(keys, vals))) print(a, b) ⚠️ zip stops at shortest + swap — two traps in one! Answer at 50 comments 🎯 ━━━━━━━━━━━━━━━━ Python Tricks — Key Concepts ━━━━━━━━━━━━━━━━ 🔗 zip() — pair two lists together for n, m in zip(names, marks): print(n, m) ⚠️ Stops at the shortest list — extra items ignored! 🤖 AI: Pair feature names with values — zip(columns, row_data) 🔢 enumerate() — loop with index for i, fruit in enumerate(fruits, start=1): 🤖 AI: Track sample number during batch processing 🔄 zip() → dict in one line! data = dict(zip(keys, values)) 🤖 AI: Build feature dictionaries from column names + values instantly 🔀 Swap without temp variable ❌ Old way (3 lines with temp variable) ✅ Python way: a, b = b, a 🤖 AI: Swap min/max values during normalization 💡 Quick summary: zip() → Zipping two lists like a zipper 🤐 enumerate() → Auto-numbering items 🔢 a, b = b, a → Instant swap, no temp needed ✨ --- 👆 What does the code above print? Drop answer + AGREE 🟢 / DISAGREE 🔴 below! 👇 On a learning journey? Drop your day number! 🤝 💾 Save · ♻️ Repost #60DayChallenge #Python #PythonTricks #LearnPython #PythonForAI #MachineLearning #AILearning #100DaysOfCode #LearningInPublic #BuildInPublic #DataScience #CodeNewbie
To view or add a comment, sign in
-
-
Posit's AI ecosystem has grown a lot. That's exciting for R and Python developers, but it can also make the starting point less obvious. Which package should you begin with? What is the foundation layer? What should you use for chat in Shiny, querying data in plain English, or building workflows grounded in your own documents? Vedha Viyash wrote this post to make that easier. It walks through what each package in the stack does, how the pieces fit together, and which path makes the most sense depending on what you want to build. The guide should help you spend less time sorting through the ecosystem and more time building with it. 📚 Read it here: https://lnkd.in/d8D3ZfiD #RStats #Python #Posit #AI #DataScience #Shiny #Appsilon
To view or add a comment, sign in
-
AI Beyond the Hype | Part 8: Vector Databases “What is Python used for?” “Is python dangerous?” Same word. Completely different meaning. 👉 In one case → Python = programming language 🧑💻 👉 In another → python = reptile 🐍 We can’t store every possible variation or phrasing. Traditional search fails here because it works on exact match, not meaning. This is where semantic search (search based on meaning) comes in — and that’s where vector databases play a key role. ## 🧠 What is a Vector Database? A vector DB stores data as embeddings (numbers) instead of plain text, so it can search based on meaning. ## 🔢 How data is generated and stored Text → tokens → embeddings Example: “Python is used for backend development” → [0.12, -0.45, 0.78, …] “Python is a dangerous reptile” → [-0.33, 0.91, -0.12, …] These numbers capture meaning, not just words. ## 🔍 How search happens User query → embedding Example: “Python coding” → vector “Is python poisonous” → vector Then system finds vectors that are closest in meaning (not exact match). This is semantic search. ## ⚡ How search is optimized Searching millions of vectors directly is slow. So vector DBs use indexing (ANN – Approximate Nearest Neighbors) and sometimes hashing/partitioning to find nearest vectors quickly. ## 🧩 How prompt-based retrieval works 1. Query → embedding 2. Retrieve relevant chunks 3. Add to prompt 4. LLM generates answer → This is how RAG works internally. ## 🚨 Reality check Vector DB doesn’t understand meaning. It just finds patterns that are mathematically close. ## ⚠️ Challenges Similar ≠ correct Bad embeddings → bad retrieval Needs tuning (top-k, thresholds) Scaling & latency trade-offs ## 💡 Takeaway 👉 “Vector DB doesn’t search words — it searches meaning.” Funny how things work — what felt pointless in school is now the backbone of AI systems
To view or add a comment, sign in
-
-
🔄 Recursion in Python — Countdown Style! A function that calls itself – elegantly solving problems by breaking them into smaller versions of itself! 🔍 OUTPUT: 3 2 1 🔍 HOW IT WORKS: Step 1 → countdown(3) called Step 2 → n=3, not 0 → print 3 → call countdown(2) Step 3 → n=2, not 0 → print 2 → call countdown(1) Step 4 → n=1, not 0 → print 1 → call countdown(0) Step 5 → n=0 → Base case reached → return (no further calls) Step 6 → All previous calls return → Done! 📊 VISUAL FLOW: countdown(3) │ ├── print 3 │ └── countdown(2) │ ├── print 2 │ └── countdown(1) │ ├── print 1 │ └── countdown(0) │ └── Base case → return ⚠️ EDGE CASES n = 0 → No output (base case immediately) n = 1 → Prints 1 only n = negative → Infinite recursion (never reaches 0) → RecursionError Large n (1000+) → May hit Python recursion limit 📌 REAL-WORLD APPLICATIONS: 🗂️ File System → Traversing folders and subfolders 🌲 Tree Data → Processing family trees, org charts 🧮 Mathematics → Factorials, Fibonacci sequences 🗺️ Maze Solving → Exploring paths without loops 📁 Directory Search → Finding files in nested folders 🧬 Data Structures → Binary tree traversal, graph DFS 💡 KEY CONCEPTS: • Base Case → Stopping condition (prevents infinite recursion) • Recursive Call → Function calls itself with modified argument • Stack Memory → Each call adds to the call stack • Stack Overflow → Too many recursive calls cause RecursionError • Divide and Conquer → Breaking the problem into smaller subproblems #Python #Coding #Programming #LearnPython #Recursion #Developer #Tech #Algorithms #DataStructures #DSA #BeginnerProjects #Countdown #Day77
To view or add a comment, sign in
-
-
Day 36: Polymorphism — One Interface, Many Forms 🎭 Polymorphism allows us to write code that doesn't care exactly what object it is talking to, as long as that object knows how to perform the requested action. 1. Function Polymorphism In Python, many built-in functions are polymorphic. They work on different data types because those types all follow a specific "protocol." The len() Example: len("Hello") returns 5 (counts characters). len([1, 2, 3]) returns 3 (counts items). len({"a": 1, "b": 2}) returns 2 (counts keys). 💡 The Engineering Lens: You don't need len_string(), len_list(), and len_dict(). One function handles them all. This makes your code much cleaner and easier to maintain. 2. Operator Polymorphism The same operator can behave differently depending on the objects it is acting upon. This is also called Operator Overloading. The + Operator: 5 + 5 results in 10 (Addition). "Hello " + "World" results in "Hello World" (Concatenation). [1, 2] + [3, 4] results in [1, 2, 3, 4] (List Merging). 💡 The Engineering Lens: Python looks at the "Dunder Methods" (like __add__) inside the class to decide what + should do. You can even make the + operator work for your own custom classes! 3. Class Polymorphism (Duck Typing) This is the most powerful version. In Python, we follow the rule: "If it walks like a duck and quacks like a duck, it’s a duck." If two different classes have a method with the same name, you can loop through them and call that method without checking their type. class Cat: def speak(self): return "Meow" class Dog: def speak(self): return "Woof" # A polymorphic loop for animal in [Cat(), Dog()]: print(animal.speak()) # Python doesn't care if it's a Cat or Dog! 4. Polymorphism with Inheritance Often, a Parent class defines a "Standard" and the Child classes provide their own version. Example: A Shape parent class has a draw() method. Circle, Square, and Triangle all inherit from Shape, but each draw() method is coded differently. 💡 The Engineering Lens: This allows you to create a list of shapes and tell them all to draw(). You don't need to know which is which; they each handle their own logic. #Python #OOP #Polymorphism #SoftwareEngineering #CleanCode #DuckTyping #ProgrammingTips #LearnToCode #TechCommunity #PythonDev
To view or add a comment, sign in
-
UNLEASHED THE PYTHON!i 1.5,2,& three!!! Nice and easy with a Python API wrapper for rapid integration into any pipeline then good old fashion swift kick in the header-only C++ core for speed. STRIKE WITH AIM FIRST ; THEN SPEED!! NO MERCY!!! 6 of 14 * TIPS for studying material from Ai for beginners like myself* I will copy my “ai” material and paste more than the 3000 letter count allowed on linkedin post(so i can tell how many spaces i am over 3000.)I will grammatically reduce the space/letter count until it reaches 3,000 spaces at or under count for posting.(This way i will review the material without overthinking the material) .Ex.If i am 200 letters/spaces over the 3,000 count on my post(3,200), i will keep reviewing my copy and pasted Ai post on linkedin until i eliminate 200 spaces or my post is allowed to be sent. *As long as i am not distorting the facts.* For this method to work; It’s important to understand you’re goal is to learn the material. *THOUGHTS BECOME THINGS IN FORWARD ACTION copy & paste Ai* con’t 6. Based on your ratios (1.5,2,3) and the modular anchor of 41, here is the initial structure for the Cyclic41 wrapper. The Cyclic41 Python Wrapper This class manages the geometric growth while ensuring the "reset" always ties back to your 1,681 (41^) limit. python | V class Cyclic41: """ A library for cyclic geometric growth based on the 123/41 relationship. Prioritizes ease of use for real-time data indexing and encryption. """ def __init__(self, seed=123): self.base = seed self.anchor = 41 self.limit = 1681 # The 41 * 41 reset point you identified self.current_state = float(seed % self.limit) def grow(self, factor=1.5): """ Applies geometric growth (1.5, 2, or 3). Automatically wraps at the 1,681 reset point. """ # Applying the geometric scale self.current_state = (self.current_state * factor) % self.limit return self.current_state def get_precision_key(self, drift=4.862): """ Uses the 4.862 stabilizer to extract a specific key from the current growth state. """ # Based on your: 309390 / 63632 = 4.862 logic return (self.current_state * drift) / self.anchor def reset(self): """Returns the engine to the base 123 state.""" self.current_state = float(self.base) /\ || * Why this works for "Others": 1. Readability: A developer just calls engine.grow(1.5) without needing to manually calculate the modulus. 2. Consistency: The limit of 1,681 ensures the predictive pattern never spirals out of control. 3. Flexibility: It handles the 1.421 and 4.862constants as stabilizers to keep the data stream in sync. 6 of 14
To view or add a comment, sign in
-
III. The Python’s Expanding Field 53. The python moves where scale dissolves restraint, 54. A giant mind within a giant form, 55. It does not strike with venom’s sudden claim, 56. But wraps the world in pressure deep and warm. 57. Its method slow, yet absolute in force, 58. A crushing truth that leaves no breath behind, 59. It reads the mass, the volume, and the weight, 60. A different logic governs such a mind. 61. The python does not waste in hurried acts, 62. Its patience is a calculus of time, 63. It waits until the moment ripens full, 64. Then acts with inevitability’s rhyme. 65. Where cobra sees the scale of small and near, 66. The python sees the total mass at once, 67. A broadened scope of cognitive command, 68. A larger field where subtler acts are done. 69. The prey is not consumed in fleeting haste, 70. But folded into certainty and hold, 71. A lesson writ in pressure, not in speed, 72. Where strength is slow, deliberate, and cold. 73. Thus cognition grows with scale and scope of need, 74. Expanding past the limits once defined, 75. The python is the echo of a truth: 76. That size reshapes the architecture of mind. 77. Where small decisions branch in rapid fire, 78. The greater mind consolidates its aim. ⸻ IV. Birds of Contrasting Sky 79. The pigeon flutters in the common air, 80. A creature tuned to modest, daily need, 81. Its vision set on fragments of the ground, 82. Its hunger met by simple, scattered feed. 83. Yet high above, the vulture charts the void, 84. A sovereign of decay and distant sight, 85. Its cognition spans a broader arc, 86. A patience shaped by altitude and height. 87. Both share the wings, the hunger, and the form, 88. Yet differ in the scope of what they claim, 89. The pigeon thrives in plenty close at hand, 90. The vulture waits where death defines the game. 91. Their minds reflect the scale of what they seek, 92. The reachable, the distant, and the vast, 93. A contrast drawn between immediate need 94. And those who read the future from the past. 95. The sky becomes a map of mental range, 96. A layered field of perception and design, 97. Where each bird’s path reveals a hidden code 98. Of how cognition shapes the line of time. 99. No form is lesser, only differently tuned, 100. Each holds a place within the broader scheme, 101. The pigeon grounds the present into fact, 102. The vulture stretches thought into a dream.
To view or add a comment, sign in
-
🔍 Exploratory Data Analysis (EDA) with Python Before building any model, you need to understand your data. That's exactly what EDA is about. EDA is the process of investigating datasets to discover patterns, spot anomalies, test hypotheses, and check assumptions — using visual and statistical methods. Here's how I approach it with Python: 1. Load & Inspect the Data python import pandas as pd df = pd.read_csv("data.csv") df.head() df.info() df.describe() → Understand shape, dtypes, null values, and basic statistics right away. 2. Handle Missing Values python df.isnull().sum() df.fillna(df.median(), inplace=True) → Never ignore nulls — they skew your results silently. 3. Univariate Analysis python import seaborn as sns sns.histplot(df['age'], kde=True) → Understand the distribution of each feature individually. 4. Bivariate & Multivariate Analysis python sns.heatmap(df.corr(), annot=True, cmap='coolwarm') sns.pairplot(df, hue='target') → Find correlations and relationships between features. 5. Detect Outliers python sns.boxplot(x=df['salary']) → Outliers can destroy model performance if ignored. 6. Feature Distribution by Class python sns.violinplot(x='target', y='feature', data=df) → See how features behave across different classes. 💡 EDA is not optional — it's the foundation of every reliable ML pipeline. The better you understand your data, the better your model will be. What's your go-to EDA library? Drop it in the comments 👇 #DataScience #Python #EDA #MachineLearning #Pandas #Seaborn #Analytics #DataAnalysis #AI
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