Very short and clean 3-liners in Python using self-defined mul() and pow() operations


  • 0
    O
    class Solution(object):
        def superPow(self, a, b):
            mul = lambda x,y: (x*y) % 1337
            pow = lambda x,n: reduce(mul, [x]*n, 1)
            return reduce(lambda x,y:mul(pow(x,10),pow(a%1337,y)), b, 1)
    

    mul(x, y) with mod k is very easy to define.
    pow() can be build based on mul()
    The problem can be solved using both operations.

    An equivalent but easier to understand version:

    class Solution(object):
        def superPow(self, a, b):
            def mul(x, y):
                return (x*y)%k
            def pow(a, n):
                ret = 1
                for i in range(n):
                    ret = mul(ret, a)
                return ret
            k = 1337
            a %= k
            ret = 1
            for n in b:
                ret = mul(pow(ret,10), pow(a,n))
            return ret
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.