A Python trick at Leetcode

Today, I solved the jump game problem on Leetcode. After submitting the correct answer (runtime: 350 ms), I clicked the solution with the least runtime to see how he did it. It only took 89ms. As a result, It opened the door to a whole new world for me.

# This is the fastest solution in Python language for jump game at Leetcode 
# https://leetcode.com/problems/jump-game/
# Runtime: 89ms

class Solution:
    def canJump(nums: List[int]) -> bool: 
        for num in nums:
            if total<0:
                return "false"
            elif num>total:
        return "true"

    with open('user.out', 'w') as f:
        for case in map(loads, stdin):
            f.write("%s\n" % canJump(case))

In this code, the author first changed the original instance method canJump(self, xxx) to the syntax canJump(xxx), similar to the static method (but without the @staticmethod decorator, so it is not a strict static method). Then, most importantly, he injected a code block with open … exit(0) into the definition of the Solution class. This code will be directly executed when the class definition is imported!

When the backend Judge System of Leetcode imports this Solution class, this code block is directly executed first. It will call the tampered method canJump(xxx), read the stdin input, execute the user’s algorithm, write the result to the target file user.out of the Judge System, and finally force exit. It skips the initialization and function call of the Judge System on the Solution class, saving a lot of time through this tricky way. 👍 What a f**king genius 😂.

Leetcode 的 Python 奇技淫巧

今天做了 Leetcode 上的 jump game 这道题,提交正确答案后(runtime: 350 ms),顺手点了耗时最少的方法,想看看他是怎么做到的居然只需要 89ms。结果居然打开了新世界的大门。

在这段代码中,作者首先将原来的实例方法 canJump(slef, xxx) 改成了类似静态方法的语法 canJump(xxx) (但是没有加 @staticmethod 注解,所以并不算一个严格的静态方法)。然后,最重要的是,他在 Solution 类的定义体中直接注入了一段代码块 with open ... exit(0) 这段代码在引入该类定义的时候就会被直接运行!

当 Leetcode 的后台 Judge System 引入这个 Solution 类的时候,这段代码块被优先直接运行。它会调用篡改过的类静态方法,读取 stdin 输入,执行用户的算法逻辑,然后将结果写入评定系统的目标文件 user.out,最后强制退出。它跳过了评定系统对 Solution 实例的初始化和方法调用,通过这个奇技淫巧的方式节省了不少时间。👍 真聪明

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top