Monday, 2 June 2025

Python Coding challenge - Day 526| What is the output of the following Python Code?


Code Explanation:

1. Function Definition
def rob(nums):
This defines a function called rob that takes a single parameter nums, which is a list of integers.
Each integer in nums represents the amount of money in a house.
The goal is to compute the maximum amount of money that can be robbed without robbing two adjacent houses.

2. Handle Empty Input
    if not nums:
        return 0
If the list nums is empty (i.e., there are no houses to rob), the function returns 0.
not nums is True when the list is empty.

3. Initialize State Variables
    a, b = 0, 0
These two variables represent the maximum money that can be robbed:
a: maximum money robbed up to the house before the previous one (i.e., i-2)
b: maximum money robbed up to the previous house (i.e., i-1)
Both are initially 0 since no money has been robbed yet.

4. Iterate Through Each House
    for n in nums:
This loop goes through each house (each value n in nums).
n represents the amount of money in the current house.

5. Update State Variables
        a, b = b, max(b, a + n)
This is the key logic of the algorithm.

Temporarily:
a becomes the previous value of b (previous house's max loot).
b becomes the max of:
b (not robbing current house, keep max so far)
a + n (rob current house, so we add its value to max loot up to i-2)
This ensures no two adjacent houses are robbed.

6. Return Final Result
    return b
After processing all houses, b holds the maximum money that can be robbed without violating the "no two adjacent houses" rule.

7. Function Call and Output
print(rob([2, 7, 9, 3, 1])) 
Calls the rob function with [2, 7, 9, 3, 1] as input.

Expected Output: 12

Rob house 1 (2), skip house 2, rob house 3 (9), skip house 4, rob house 5 (1) → 2 + 9 + 1 = 12

Output:

12
 

0 Comments:

Post a Comment

Popular Posts

Categories

100 Python Programs for Beginner (118) AI (152) Android (25) AngularJS (1) Api (6) Assembly Language (2) aws (27) Azure (8) BI (10) Books (251) Bootcamp (1) C (78) C# (12) C++ (83) Course (84) Coursera (298) Cybersecurity (28) Data Analysis (24) Data Analytics (16) data management (15) Data Science (217) Data Strucures (13) Deep Learning (68) Django (16) Downloads (3) edx (21) Engineering (15) Euron (30) Events (7) Excel (17) Finance (9) flask (3) flutter (1) FPL (17) Generative AI (47) Git (6) Google (47) Hadoop (3) HTML Quiz (1) HTML&CSS (48) IBM (41) IoT (3) IS (25) Java (99) Leet Code (4) Machine Learning (186) Meta (24) MICHIGAN (5) microsoft (9) Nvidia (8) Pandas (11) PHP (20) Projects (32) Python (1218) Python Coding Challenge (884) Python Quiz (342) Python Tips (5) Questions (2) R (72) React (7) Scripting (3) security (4) Selenium Webdriver (4) Software (19) SQL (45) Udemy (17) UX Research (1) web application (11) Web development (7) web scraping (3)

Followers

Python Coding for Kids ( Free Demo for Everyone)