Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
56-liner: hacking checkio solution in Creative category for Sum of Digits by przemyslaw.daniel
import inspect
def create_file(name, content):
file_descriptor = inspect.builtins.open(name, "w")
file_descriptor.write(content)
file_descriptor.close()
def sum_digits(number: str):
"""
hacking checkio by injecting, compiling and executing c code
"""
# create r_weakref.py that can be imported later on
create_file("/tmp/r_weakref.py", "import os")
# add to sys path /tmp
inspect.sys.path = ['/tmp'] + inspect.sys.path
# now we can import weakref which will link to os module
import weakref
os = weakref.os # os module isn't allowed normally
# create c file in /tmp folder
os.chdir('/tmp')
c_code = '''
#include
int main(int argc, char **argv)
{
int result = 0;
for (int index = 0; argv[1][index] != 0; ++index)
{
int over = (result + argv[1][index] - 48) / 10;
result = (over + result + argv[1][index] - 48) % 10;
}
printf("%d\\n", result);
}
'''
create_file("sum.c", c_code)
# compile first
export_cc1 = "export PATH=$PATH:/usr/lib/gcc/x86_64-linux-gnu/10/cc1"
os.system(f"{export_cc1}; gcc ./sum.c -o ./sum.exe")
# run binary
result = os.popen(f"./sum.exe {number}").read()
# don't leave a mess, cleaning
os.system("rm sum.exe")
os.system("rm sum.c")
os.system("rm r_weakref.py")
return int(result)
Oct. 1, 2022
Comments: