简体   繁体   中英

Accessing function in Python dictionary

class Solution:
    def add(x) -> int:
        return x + 1

    def sub(x) -> int:
        return x - 1

    def finalValueAfterOperations(self, operations: List[str]) -> int:
        switch = {"X++": add, "++X": add, "X--": sub, "--X": sub}
        x = 0
        for i in range(len(operations)):
            x = switch[operations[i]](x)

        return x

Getting an error while doing this:

TypeError: unsupported operand type(s) for -: 'Solution' and 'int'
    x = switch[operations[i]](self,x)
Line 20 in finalValueAfterOperations (Solution.py)
    ret = Solution().finalValueAfterOperations(param_1)

I replaced the function with "X++": lambda x : x+1 for all cases and it works. How do i make it work for function ?

It's impossible that you'd get the error you've pasted from the code you've pasted.

In any case, assuming you do wish to keep things encapsulated in a class (for whichever reason), the issue is that you'd need to either define the operations as free functions, like

from typing import List


def add(x) -> int:
    return x + 1


def sub(x) -> int:
    return x - 1


class Solution:

    def compute(self, operations: List[str], x=0) -> int:
        switch = {"X++": add, "++X": add, "X--": sub, "--X": sub}
        for op in operations:
            x = switch[op](x)

        return x


print(Solution().compute(["X++", "++X", "X--"]))

or as real methods and refer to them as such:

from typing import List


class Solution:

    def add(self, x) -> int:
        return x + 1

    def sub(self, x) -> int:
        return x - 1

    def compute(self, operations: List[str], x=0) -> int:
        switch = {"X++": self.add, "++X": self.add, "X--": self.sub, "--X": self.sub}
        for op in operations:
            x = switch[op](x)

        return x


print(Solution().compute(["X++", "++X", "X--"]))

or perhaps as @staticmethod s since you don't need self :

from typing import List


class Solution:

    @staticmethod
    def add(x) -> int:
        return x + 1

    @staticmethod
    def sub(x) -> int:
        return x - 1

    def compute(self, operations: List[str], x=0) -> int:
        switch = {"X++": self.add, "++X": self.add, "X--": self.sub, "--X": self.sub}
        for op in operations:
            x = switch[op](x)

        return x


print(Solution().compute(["X++", "++X", "X--"]))

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