Skip to content

Instantly share code, notes, and snippets.

@vishvananda
Created August 11, 2012 16:48
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vishvananda/3325686 to your computer and use it in GitHub Desktop.
Save vishvananda/3325686 to your computer and use it in GitHub Desktop.
Translator to translate a python program into an equivalent program with a very limited set of characters
import os
with open('in.py') as infile:
data = infile.read()
def encode(char, sym):
return'+'.join([sym] * ord(char))
def write(outfile, wrap, boc, eoc, sep, sym='1'):
text = sep.join([boc + encode(char, sym) + eoc for char in data])
outfile.write(wrap % text)
# 9 characters, no assignment
# exc1+hr()
with open('out.py', 'w') as outfile:
write(outfile, "exec(%s)", "chr(", ")", "+")
# 9 characters, no assignment, three letters
# exc1+'%() (or, trivially exc1+"%())
with open('out2.py', 'w') as outfile:
write(outfile, "exec(%s)", "'%c'%(", ")", "+")
# 9 characters, 8 if you don't count white space
# exc1+'%=\n (or, trivially exc1+"%=\n)
with open('out3.py', 'w') as outfile:
write(outfile, "e=''\n%s\nexec''+e", "c=", "\ne+='%c'%c", "\n")
# 9 characters
# exc1+'%=; (or, trivially exc1+"%=;)
with open('out4.py', 'w') as outfile:
write(outfile, "e='';%s;exec''+e", "c=", ";e+='%c'%c", ";")
# 11 characters: no numbers, no assignment, three symbols
# excnothr+()
with open('out5.py', 'w') as outfile:
write(outfile, "exec(%s)", "chr(", ")", "+", '(not())')
# 7 characters, abuse the filesystem
# imp ort
with open('out6.py', 'w') as outfile:
outfile.write("import i")
with open('i.py', 'w') as outfile:
outfile.write(data)
# 14 characters, abuse the filesystem, requires /usr/local/bin in path
# imp ortsye.'()\n
os.system('ln -s `which python` /usr/local/bin/yt')
with open('out7.py', 'w') as outfile:
outfile.write("import os\n")
outfile.write("os.system('yt testy')")
with open('testy', 'w') as outfile:
outfile.write(data)
if os.path.exists('/usr/local/bin/yt') or os.path.islink('/usr/local/bin/yt'):
os.unlink('/usr/local/bin/yt')
@dgrtwo
Copy link

dgrtwo commented Aug 27, 2012

The 7-character solution definitely strikes me as cheating!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment