Wei Xia
Wei Xia

Reputation: 533

Why do I get this syntax error by using "min()"?

Sorry first if this question is too simple. Just start to learn Python.

So here is my code:

class Solution:
    def minCostClimbingStairs(self, cost: List[int]) -> int:
        n = len(cost)
        m = [0] * n

        def dp(self, cost, m, i):
            dp1 = dp(cost, m, i - 1) + cost[i - 1]
            dp2 = dp(cost, m, i - 2) + cost[i - 2]
            return m[i] = min(dp1, dp2)

        return dp(cost, m, n)

While I try to run it, it tells me SyntaxError: invalid syntax in line of code return m[i] = min(dp1, dp2)

=======> MODIFIED AFTER FEEDBACK

class Solution:
    def minCostClimbingStairs(self, cost: List[int]) -> int:
        m = [0] * (len(cost) + 1)

        def dp(cost, m, i):
            if i <= 1:
                return 0
            if m[i] > 0:
                return m[i]

            dp1 = dp(cost, m, i - 1) + cost[i - 1]
            dp2 = dp(cost, m, i - 2) + cost[i - 2]
            m[i] = min(dp1, dp2)

            return m[i]

        return dp(cost, m, len(cost))

Upvotes: 0

Views: 102

Answers (1)

Luka Mesaric
Luka Mesaric

Reputation: 677

You cannot assign and return a variable at once in Python, unlike in some other languages. Split that line into two.

m[i] = min(dp1, dp2)
return m[i]

You do not need self in dp function since it is a local function and not a class method.

Upvotes: 1

Related Questions