Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@ahojukka5
Created March 19, 2021 10:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ahojukka5/201fe5194d6415a10c6d4953262bbab6 to your computer and use it in GitHub Desktop.
Save ahojukka5/201fe5194d6415a10c6d4953262bbab6 to your computer and use it in GitHub Desktop.
import ctypes
import os
import subprocess
import tempfile
__code__ = """
#include <stdbool.h>
bool check(unsigned long long int n) {
int sum = 0;
while (n > 0) {
sum += n % 10;
n /= 10;
}
return sum % 7 == 0;
}
"""
path = tempfile.mkdtemp()
cfile = os.path.join(path, "lib.c")
sofile = os.path.join(path, "lib.so")
open(cfile, "w").write(__code__)
__cmd__ = "gcc -O3 -shared -o %s %s" % (sofile, cfile)
if os.environ.get("DEBUG"):
print(__cmd__)
subprocess.run(__cmd__.split(" "))
lib = ctypes.CDLL(sofile)
lib.check.restype = ctypes.c_bool
lib.check.argtypes = [ctypes.c_ulonglong]
check = lib.check
if __name__ == "__main__":
print(check(14)) # False
print(check(16)) # True
print(check(123)) # False
print(check(777)) # True
print(check(9999999)) # True
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment