4
\$\begingroup\$

You are given a list of houses on a street, with the numeric value representing the amount of money stashed away in each house.

Write a method to find the maximum amount of money you can steal. You cannot steal from any two adjacent houses, otherwise you will be caught! Use Dynamic Programming!

Examples:

  • robbery([60, 50, 20, 32, 20, 50])142

  • robbery([40, 25, 25, 30])70

I would like to ask for a review of the following solution.

def robbery(amounts):
    amounts = iter(amounts)
    prev, total = 0, next(amounts, 0)
    for x in amounts: prev, total = total, max(total, prev + x)
    return total

Here's my code on Gist: https://gist.github.com/Jeffchiucp/6dbd481ce4bc208e6da68bc8e920bf3f

\$\endgroup\$
5
\$\begingroup\$

The algorithm is conceptually fine: it's simple and it works.

I don't like the use of iter() and next(), though. When you write for x in amounts, that will already treat amounts as an iterator. The only benefit you get from an explicit amount = iter(amounts), then, is the ability to write next(amounts, 0). And the only reason for writing next(amounts, 0) is to handle the special case where the input is an empty list. You could just as well handle that by pretending that there is always another leading house with 0 money.

def robbery(amounts):
    prev, total = 0, 0
    for amount in amounts:
        prev, total = total, max(total, prev + amount)
    return total

The for loop would be better written with the conventional indentation.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.