Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python code with Chinese characters exec()

Tags:

python

exec(bytes('㵮湩⡴湩異⡴⤩瀊楲瑮嬨畳⡭慭⡰湩ⱴ瑳⡲⩮㈪⤩Ⱙ⩮㈪孝污⡬╮潦⁲湩爠湡敧㈨測⤩⥝','u16')[2:])

What exactly does this do? On Codingame.com, people submit this Python code like this regularly.

My guess is that they've somehow broken down their Python code in such a way that these characters represent their code and executes it (which is a hacky way to win a "shortest mode" competition on the website).

like image 847
zapshe Avatar asked Aug 31 '25 10:08

zapshe


1 Answers

The string of chinese characters is python code encoded with UTF-8 and decoded as UTF-16.

Decoded Python Code

 n=int(input())
 print([sum(map(int,str(n**2))),n**2][all(n%m for m in range(2,n))])  

Why?

You can cram the same information in less characters to get an edge on a 'code golf' competition where the char count matters

How?

Here's some python code that generates that string:

>>> code = 'n=int(input())\nprint([sum(map(int,str(n**2))),n**2][all(n%m for m in range(2,n))])'
>>> print(code.encode('u8').decode('u16'))
㵮湩⡴湩異⡴⤩瀊楲瑮嬨畳⡭慭⡰湩ⱴ瑳⡲⩮㈪⤩Ⱙ⩮㈪孝污⡬╮潦⁲湩爠湡敧㈨測⤩⥝

Could be extended for any code:

>>> code = 'print(\'hello World!!\')'.encode('u8').decode('u16')
>>> print(code)
牰湩⡴栧汥潬圠牯摬℡⤧

Test it

We can run this command to 'unpack' and execute:

>>> exec(bytes("牰湩⡴栧汥潬圠牯摬℡⤧","u16")[2:])
hello World!!
like image 157
JuanMa Cuevas Avatar answered Sep 02 '25 23:09

JuanMa Cuevas