def generate(num, prompt_default=True): """Generates Python file for a problem.""" p = Problem(num) problem_text = p.text msg = "Generate file for problem %i?" % num click.confirm(msg, default=prompt_default, abort=True) # Allow skipped problem files to be recreated if p.glob: filename = str(p.file) msg = '"{}" already exists. Overwrite?'.format(filename) click.confirm(click.style(msg, fg='red'), abort=True) else: # Try to keep prefix consistent with existing files previous_file = Problem(num - 1).file prefix = previous_file.prefix if previous_file else '' filename = p.filename(prefix=prefix) header = 'Project Euler Problem %i' % num divider = '=' * len(header) text = '\n'.join([header, divider, '', problem_text]) content = '\n'.join(['"""', text, '"""']) with open(filename, 'w') as f: f.write(content + '\n\n\n') click.secho('Successfully created "{}".'.format(filename), fg='green') # Copy over problem resources if required if p.resources: p.copy_resources()
def verify(num, filename=None, exit=True): """Verifies the solution to a problem.""" p = Problem(num) filename = filename or p.filename() if not os.path.isfile(filename): # Attempt to verify the first problem file matched by glob if p.glob: filename = str(p.file) else: click.secho('No file found for problem %i.' % p.num, fg='red') sys.exit(1) solution = p.solution click.echo('Checking "{}" against solution: '.format(filename), nl=False) cmd = (sys.executable or 'python', filename) start = clock() proc = subprocess.Popen(cmd, stdout=subprocess.PIPE) stdout = proc.communicate()[0] end = clock() time_info = format_time(start, end) # Return value of anything other than 0 indicates an error if proc.poll() != 0: click.secho('Error calling "{}".'.format(filename), fg='red') click.secho(time_info, fg='cyan') # Return None if option is not --verify-all, otherwise exit return sys.exit(1) if exit else None # Decode output if returned as bytes (Python 3) if isinstance(stdout, bytes): output = stdout.decode('ascii') # Split output lines into array; make empty output more readable output_lines = output.splitlines() if output else ['[no output]'] # If output is multi-lined, print the first line of the output on a # separate line from the "checking against solution" message, and # skip the solution check (multi-line solution won't be correct) if len(output_lines) > 1: is_correct = False click.echo() # force output to start on next line click.secho('\n'.join(output_lines), bold=True, fg='red') else: is_correct = output_lines[0] == solution fg_colour = 'green' if is_correct else 'red' click.secho(output_lines[0], bold=True, fg=fg_colour) click.secho(time_info, fg='cyan') # Remove any suffix from the filename if its solution is correct if is_correct: p.file.change_suffix('') # Exit here if answer was incorrect, otherwise return is_correct value return sys.exit(1) if exit and not is_correct else is_correct
def generateFile(problem, filename=None, content=None, correct=False): """ Uses Problem.solution to generate a problem file. The correct argument controls whether the generated file is correct or not. """ p = Problem(problem) filename = filename or p.filename() with open(filename, 'w') as f: if correct: f.write('print({})'.format(p.solution)) elif content: f.write(content)
def generate(num, prompt_default=True): """Generates Python file for a problem.""" def wrap(text, wrap_len): """Wraps text at given character width. Args: text (str): text to wrap wrap_len (int): character width at which to wrap Returns: String with newlines inserted as appropriate """ if len(text) > wrap_len: words = iter(text.split()) wrapped_lines = [] wrapped_line = next(words) # assume 1st word is shorter than wrap_len for word in words: if len(wrapped_line) + len(word) < wrap_len: # < rather than <= to account for 1 char space wrapped_line = ' '.join([wrapped_line, word]) else: wrapped_lines.append(wrapped_line) wrapped_line = word wrapped_lines.append(wrapped_line) return '\n'.join(wrapped_lines) else: return text p = Problem(num) problem_text = p.text msg = "Generate file for problem %i?" % num click.confirm(msg, default=prompt_default, abort=True) # Allow skipped problem files to be recreated if p.glob: filename = str(p.file) msg = '"{}" already exists. Overwrite?'.format(filename) click.confirm(click.style(msg, fg='red'), abort=True) else: # Try to keep prefix consistent with existing files previous_file = Problem(num - 1).file prefix = previous_file.prefix if previous_file else '' filename = p.filename(prefix=prefix) header = 'Project Euler Problem {}\n\n{}'.format(num, wrap(p.title, 76)) divider = '=' * len(header.split('\n')[-1]) text = '\n'.join([header, divider, '', problem_text]) content = '\n'.join([ '#!/usr/bin/env python', '# -*- coding: utf-8 -*-', '', '"""', text, '"""', '', 'def problem_{}():'.format(num), ' response = 0', ' print(response)', '', "if __name__ == '__main__':", ' problem_{}()'.format(num) ]) with open(filename, 'w') as f: f.write(content) click.secho('Successfully created "{}".'.format(filename), fg='green') # Copy over problem resources if required if p.resources: p.copy_resources()