简体   繁体   中英

Python lambda dp calculation

I am trying to understand below code snippet, for each value of i, what are all the two arguments passed to min() ? appreciate if you could explain how the dp[i] computation could be expanded?

class Solution(object):

    def coinChange(self, coins, amount):
        MAX = float('inf')
        dp = [0] + [MAX] * amount
        print(dp)

        for i in range(1, amount + 1):
            dp[i] = min([dp[i - c] if i - c >= 0 else MAX for c in coins]) + 1

        print(dp)
        return [dp[amount], -1][dp[amount] == MAX]

A lot of things are happening here. The min() method is receiving a python list as an argument.

This python list is created through list comprehension . It helps to start from the back. The list comprehension is saying "For every value c in the iterable coins , append the value dp[i - c] to my list if the boolean i - c >=0 is True . Otherwise, append the value MAX .

In other words, the line [dp[i - c] if i - c >= 0 else MAX for c in coins] is equivalent to

def makelist(dp,i,MAX,coins):
    ret = []
    for c in coins:
        if i - c >= 0:
            ret.append(dp[i-c])
        else:
            ret.append(MAX)
    return ret

The min() method will be performed on this list once it is complete, which simply find the smallest value in the list

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM