project-euler/main.py

67 lines
1.8 KiB
Python
Executable File

#!/usr/bin/env python3
import os
import subprocess
import re
import sys
exs = ['py', 'exe']
sol_pattern = re.compile(r'(\d+)_.+\.(?:{})'.format('|'.join(exs)))
def print_bar(i, count):
step = 1
while count // step > 80:
step += 1
w = count // step
j = i // step
bar = '[{}{}] {}/{}'.format('#'*(j), '.'*(w - j), i, count)
print(bar, end='\r')
return len(bar)
def run(fn, cmd=None):
if cmd == None:
ext = fn.split('.')[-1]
if ext == 'py':
with open(fn) as f:
shebang = f.read().lstrip().split('\n')[0]
if shebang[:2] != '#!':
cmd = 'pypy '
else:
cmd = shebang[2:].replace('python', 'pypy') + ' '
else:
cmd = './'
proc = subprocess.run(cmd + fn, shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
if len(proc.stderr) > 0:
if 'pypy' in cmd:
print('warning : pypy failed. trying cpython', file=sys.stderr)
print(proc.stderr)
return run(fn, cmd = cmd.replace('pypy', 'python'))
print('error : error while running solution')
print(proc.stderr)
return proc.stdout.decode('utf-8').rstrip().split('\n')[-1]
def main():
matches = map(sol_pattern.fullmatch, os.listdir('.'))
fs = {int(m.group(1)) : m.group(0) for m in matches if m != None}
solved = sorted(fs.keys())
print('Num Solution')
print('---------------')
for i, x in enumerate(solved, start=1):
bar_len = print_bar(i, len(fs))
f = fs[x]
r = run(f)
fst_str = '{:>3d} {}'.format(x, r)
print(fst_str, end='')
line = ' ' * (bar_len - len(fst_str))
print(line)
if __name__ == '__main__':
main()