code
stringlengths
1
1.49M
vector
listlengths
0
7.38k
snippet
listlengths
0
7.38k
# sandbox for ast... import ast source = '''s=s+x''' node = ast.parse(source, mode='exec') from pprint import pprint pprint( ast.dump(node, annotate_fields=False, include_attributes=False) ) #~ print (eval(compile(node, '<string>', mode='eval'))) """ Module( body=[ Assign( targets=[Name(id='s', ctx=Store())], value=BinOp( left=Name(id='s', ctx=Load()), op=Add(), right=Name(id='x', ctx=Load()) ) ) ] ) """ def get_assignment_target(linecode): """ >>> print( get_assignment_target("pinigai = laikas * atlyginimas") ) pinigai """ node = ast.parse(linecode, mode='exec') if (isinstance(node.body[0], ast.Assign)): assignment = node.body[0] return assignment.targets[0].id #~ print( get_assignment_target("pinigai == laikas * atlyginimas") ) """ from ast import * stmt = Module([Assign([Name('s', Store())], BinOp(Name('s', Load()), Add(), Name('x', Load())))]) print(isinstance(stmt, AST) ) print( getattr(stmt, 'body')) if (isinstance(stmt.body[0], ast.Assign)): print("Assignment") assignment = stmt.body[0] print( stmt.body[0]._fields) print( assignment.targets[0].id ) #~ print (stmt['body']) #~ if isinstance( stmt['body'] ) #~ print(stmt._fields[0]._fields) """
[ [ 1, 0, 0.0392, 0.0196, 0, 0.66, 0, 809, 0, 1, 0, 0, 809, 0, 0 ], [ 14, 0, 0.0784, 0.0196, 0, 0.66, 0.1429, 703, 1, 0, 0, 0, 0, 3, 0 ], [ 14, 0, 0.098, 0.0196, 0, 0...
[ "import ast", "source = '''s=s+x'''", "node = ast.parse(source, mode='exec')", "from pprint import pprint", "pprint( ast.dump(node, annotate_fields=False, include_attributes=False) )", "\"\"\"\nModule(\n body=[\n Assign(\n targets=[Name(id='s', ctx=Store())],\n value=BinOp(...
# http://stackoverflow.com/questions/1515357/simple-example-of-how-to-use-ast-nodevisitor #~ http://docs.python.org/3/library/ast.html #~ http://eli.thegreenplace.net/wp-content/uploads/2009/11/codegen.py #~ http://dev.pocoo.org/hg/sandbox/file/852a1248c8eb/ast/codegen.py #~ https://github.com/llvmpy/llvmpy/blob/master/llvm_cbuilder/translator.py code_example1 = """ x = 5 x = x + 3 """ code_example2 = """ L = [4, 5, 2] if L[0] > 4: print( L[0] ) L[1] = 10 """ code_example3b = """ A = [2, 0, 4, 3] max = 0 for x in A: if x > max : max = x print( x, max ) """ code_example3 = """ A = [2, 0, 4, 3] max = 0 for z in range(4): if A[z] > max : max = A[z] print( z, max ) """ # """ ----------------------------------------------- int A = {2, 0, 4, 3}; int max = 0; for (int z=0; z<N; z++) { if (A[z] > max) { max = A[z]; cout << z << " " << max << endl; } } """ code_example4 = """ a = "labas" M = [ [2, 0, 3], [1, 4, 3] ] n = len(M[0]) # @cpp/len(M[0])/3/ for i in range(n): if M[0][i] > M[1][i] : max = M[0][i] print( i, max ) del M[0] M.append( 5 ) def fun(x, y, a=15): return x*y+a """ import ast #~ t = ast.parse('d[x] += v[y, x]') import re def custom_changes(src, type='cpp'): lines = src.split('\n') for i, line in enumerate(lines): if '#' in line: code, comment = line.split('#', 1) if '@'+type in comment: match = re.search('@'+type+r"/(.*?)/(.*?)/", comment) if match: search, replace = match.group(1), match.group(2) # escape search for char in "\\(){}[].*?!^$": search = search.replace(char, '\\'+char) search = eval("r'%s'"%search) # make string raw lines[i] = re.sub(search, replace, line) #~ print( 'SUB', repr(search), repr(replace), lines[i] ) else: print( "BAD custom changes", '@'+type , i, line ) return '\n'.join(lines) ######################## def find_extraindentation(src): extra_indent = 0 for line in src.split('\n'): if line.strip(' \t'): extra_indent = len(line)-len(line.lstrip(' ')) return extra_indent def dedent(src, indentation): dedented_lines = [] for line in src.split('\n'): if line.strip(' \t'): prefix = line[:indentation] line = line[indentation:] if prefix.strip(' \t'): # sometimes spacing is wrong and strip too much line = prefix.strip(' \t') + line dedented_lines.append(line) src = '\n'.join( dedented_lines ) return src def indent(src, indentation): indented_lines = [] for line in src.split('\n'): if line.strip(' \t'): line = ' '*indentation + line indented_lines.append(line) src = '\n'.join( indented_lines ) return src import codegen_cpp from pygments.lexers import PythonLexer, CppLexer pylexer = PythonLexer(ensurenl=False) def collect_py_comments(src): comments = {} for lineno, line in enumerate(src.split('\n')): for ttype, tval in pylexer.get_tokens( line ): if str(ttype) == 'Token.Comment': comments[lineno+1] = tval return comments def convert(src, GIFT=True): #~ print("\n\n CONVERTING \n\n", src, "\n-------------------------\n") src = custom_changes(src, 'cpp') extra_indentation = find_extraindentation(src) src = dedent(src, extra_indentation) t = ast.parse(src) #~ print("\n\n---DUMP") #~ print( ast.dump(t, annotate_fields=True, include_attributes=False).replace("body=[", "body=[\n ") .replace("], ", "],\n ") .replace(")), ", ")),\n ") ) cpp_src = codegen_cpp.to_source( t , comments=collect_py_comments(src) ) if GIFT: #~ for char in '~=#{}': # GIFT format spec characters: http://docs.moodle.org/23/en/GIFT_format#Special_Characters_.7E_.3D_.23_.7B_.7D for char in '{}': # GIFT format spec characters: http://docs.moodle.org/23/en/GIFT_format#Special_Characters_.7E_.3D_.23_.7B_.7D cpp_src.replace(char, '\\'+char) cpp_src = indent(cpp_src, extra_indentation) return cpp_src if __name__=='__main__': print(convert(code_example3b)) ################## src CODE here ########## #~ #~ code = custom_changes(code_example3, 'cpp') #~ #~ t = ast.parse("x = a - 4 * (b - a) ") t = ast.parse("if not x > 5: print(x>4)") #~ print("\n\n---DUMP") #~ print( ast.dump(t, annotate_fields=True, include_attributes=False).replace("body=[", "body=[\n ") .replace("], ", "],\n ") .replace(")), ", ")),\n ") ) #~ print("\n"*3, " ----- PY ------- \n\n", ) #~ import codegen #~ print ( codegen.to_source( t ) ) #~ #~ print("\n"*3, " ----- C++ ------- \n\n", ) #~ print ( codegen_cpp.to_source( t ) ) ##############################
[ [ 14, 0, 0.0571, 0.0217, 0, 0.66, 0, 908, 1, 0, 0, 0, 0, 3, 0 ], [ 14, 0, 0.0897, 0.0326, 0, 0.66, 0.0588, 798, 1, 0, 0, 0, 0, 3, 0 ], [ 14, 0, 0.1332, 0.0435, 0, 0...
[ "code_example1 = \"\"\"\nx = 5\nx = x + 3\n\"\"\"", "code_example2 = \"\"\"\nL = [4, 5, 2]\nif L[0] > 4:\n print( L[0] )\nL[1] = 10\n\"\"\"", "code_example3b = \"\"\"\nA = [2, 0, 4, 3]\nmax = 0\nfor x in A:\n if x > max : \n max = x\n print( x, max )\n\"\"\"", "code_example3 = \"\"\"\nA ...
# -*- coding: utf-8 -*- """ codegen ~~~~~~~ Extension to ast that allow ast -> CPP code generation. :copyright: Copyright 2008 by Armin Ronacher (adapted for C++ by Jurgis Pralgauskis) :license: BSD. https://pypi.python.org/pypi/codegen also similar: http://svn.python.org/view/python/trunk/Demo/parser/unparse.py?view=markup and "the missing Python AST docs" http://greentreesnakes.readthedocs.org/en/latest/ """ from ast import * BOOLOP_SYMBOLS = { And: 'and', # && Or: 'or' # || } BINOP_SYMBOLS = { Add: '+', Sub: '-', Mult: '*', Div: '/', FloorDiv: '//', Mod: '%', LShift: '<<', RShift: '>>', BitOr: '|', BitAnd: '&', BitXor: '^', #~ Pow: '**' # in cpp should translate as function } CMPOP_SYMBOLS = { Eq: '==', Gt: '>', GtE: '>=', Lt: '<', LtE: '<=', NotEq: '!=', In: 'IN /*???*//*!!!*/', #~ Is: 'is', #~ IsNot: 'is not', #~ NotIn: 'not in' } UNARYOP_SYMBOLS = { #~ Invert: '~', Not: '!', UAdd: '+', USub: '-' } ALL_SYMBOLS = {} ALL_SYMBOLS.update(BOOLOP_SYMBOLS) ALL_SYMBOLS.update(BINOP_SYMBOLS) ALL_SYMBOLS.update(CMPOP_SYMBOLS) ALL_SYMBOLS.update(UNARYOP_SYMBOLS) def to_source(node, indent_with=' ' * 4, add_line_information=False, comments={}): """This function can convert a node tree back into python sourcecode. This is useful for debugging purposes, especially if you're dealing with custom asts not generated by python itself. It could be that the sourcecode is evaluable when the AST itself is not compilable / evaluable. The reason for this is that the AST contains some more data than regular sourcecode does, which is dropped during conversion. Each level of indentation is replaced with `indent_with`. Per default this parameter is equal to four spaces as suggested by PEP 8, but it might be adjusted to match the application's styleguide. If `add_line_information` is set to `True` comments for the line numbers of the nodes are added to the output. This can be used to spot wrong line number information of statement nodes. """ generator = SourceGenerator(indent_with, add_line_information, comments) generator.visit(node) #~ print (generator.result) return ''.join(generator.result) class SourceGenerator(NodeVisitor): """This visitor is able to transform a well formed syntax tree into python sourcecode. For more details have a look at the docstring of the `node_to_source` function. """ def __init__(self, indent_with=' '*4, add_line_information=False, comments_dict={}): self.result = [] self.indent_with = indent_with self.add_line_information = add_line_information self.indentation = 0 self.new_lines = 0 self.defined_variables = {} # TODO: scopes #~ self.variable_values = {} # TODO: scopes self.varaible2indexed_substitutions = {} # TODO: scopes self.opstack=[] self.comments=comments_dict # dictionary self.commentPending = None def dump_node(self, node): self.write('\n') n = len(self.result) #~ newline_end = ['\n'] if self.result[-1] == '\n' else [] self.visit(node) result = self.result[n:] self.result = self.result[:n] return ''.join(result).lstrip('\n') def write(self, x): if self.new_lines: # inject comments -- before next newline if self.commentPending and self.commentLineEnd: self.result.append(' //'+self.commentPending ) self.commentPending = None self.commentLineEnd = True if self.result: self.result.append('\n' * self.new_lines) self.result.append(self.indent_with * self.indentation) self.new_lines = 0 self.result.append(x) def newline(self, node=None, extra=0): self.new_lines = max(self.new_lines, 1 + extra) if hasattr(node, 'lineno') and node.lineno in self.comments: self.commentPending = self.comments[node.lineno] # we "pass" it via commentPending, because in "write" we don't have "lineno" self.commentLineEnd = False #~ self.write('// ' +str(node.lineno) +' ' + self.comments[node.lineno]) #~ self.new_lines = 1 if node is not None and self.add_line_information: self.write('// line: %s' % node.lineno) self.new_lines = 1 def body(self, statements): self.new_line = True self.indentation += 1 for stmt in statements: self.visit(stmt) self.indentation -= 1 def body_or_else(self, node): self.body(node.body) if node.orelse: self.newline() self.write('else:') self.body(node.orelse) def signature(self, node): want_comma = [] def write_comma(): if want_comma: self.write(', ') else: want_comma.append(True) padding = [None] * (len(node.args) - len(node.defaults)) for arg, default in zip(node.args, padding + node.defaults): write_comma() self.write_type() # int #~ self.visit(arg) self.write(arg.arg) # changed in py3: arg.id is empty if default is not None: self.write('=') self.visit(default) if node.vararg is not None: write_comma() self.write('*' + node.vararg) if node.kwarg is not None: write_comma() self.write('**' + node.kwarg) def decorators(self, node): for decorator in node.decorator_list: self.newline(decorator) self.write('@') self.visit(decorator) # Statements #~ def visit_Arg(self, node): #~ # arg = (identifier arg, expr? annotation) #~ self.write(node.arg) def visit_Assign(self, node): self.newline(node) for idx, target in enumerate(node.targets): if idx: self.write(', ') #~ self.visit(target) self.visit_VariableDef_cpp(target, node.value) self.write(' = ') self.visit(node.value) self.write(';') def visit_AugAssign(self, node): self.newline(node) self.visit(node.target) self.write(BINOP_SYMBOLS[type(node.op)] + '=') self.visit(node.value) self.write(';') def visit_ImportFrom(self, node): self.newline(node) self.write('from %s%s import ' % ('.' * node.level, node.module)) for idx, item in enumerate(node.names): if idx: self.write(', ') self.write(item) def visit_Import(self, node): self.newline(node) for item in node.names: self.write('import ') self.visit(item) def visit_Expr(self, node): self.newline(node) self.generic_visit(node) def visit_FunctionDef(self, node): self.newline(extra=1) self.decorators(node) self.newline(node) self.write('int %s(' % node.name) # be carefull with other <type>s self.signature(node.args) self.write('){') self.body(node.body) self.newline(node) self.write('}') def visit_ClassDef(self, node): have_args = [] def paren_or_comma(): if have_args: self.write(', ') else: have_args.append(True) self.write('(') self.newline(extra=2) self.decorators(node) self.newline(node) self.write('class %s' % node.name) for base in node.bases: paren_or_comma() self.visit(base) # XXX: the if here is used to keep this module compatible # with python 2.6. if hasattr(node, 'keywords'): for keyword in node.keywords: paren_or_comma() self.write(keyword.arg + '=') self.visit(keyword.value) if node.starargs is not None: paren_or_comma() self.write('*') self.visit(node.starargs) if node.kwargs is not None: paren_or_comma() self.write('**') self.visit(node.kwargs) self.write(have_args and '):' or ':') self.body(node.body) def visit_If(self, node): self.newline(node) self.write('if (') self.visit(node.test) self.write('){') self.body(node.body) self.newline(node); self.write('}') # finish block for cpp while True: else_ = node.orelse if len(else_) == 1 and isinstance(else_[0], If): node = else_[0] self.newline() self.write('else if ') self.visit(node.test) self.write('{') self.body(node.body) self.newline(node); self.write('}') # finish block for cpp else: if else_: self.newline() self.write('else {') self.body(else_) self.newline(node); self.write('}') # finish block for cpp break def visit_VariableDef_cpp(self, target, value): if isinstance(target, Name): # variable definition. TODO: arrays indicators... if not target.id in self.defined_variables: #~ self.defined_variables.append(target.id) self.defined_variables[target.id] = value self.write_type(value) self.visit(target) self.write_dimension(value) else: self.visit(target) else: self.visit(target) def write_dimension(self, value): if isinstance(value, List): self.write('[%s]'%len(value.elts) ) # for multidimentional - Matrixes if len(value.elts) > 0: # TODO # could do recursively: value_inner = value.elts[0] if isinstance(value_inner, List): max_len = max( [len(x.elts) for x in value.elts if isinstance(x, List)] ) self.write('[%s]' % max_len) def write_type(self, value=0): if isinstance(value, Num): self.write('int ') elif isinstance(value, Str): self.write('string ') elif isinstance(value, List): #~ self.write('int []') if len(value.elts) > 0: # could do recursively: value = value.elts[0] if isinstance(value, Num): self.write('int ') elif isinstance(value, Str): self.write('string ') else: self.write('int ') # default else: self.write('int ') # default else: self.write('int ') # default def visit_For(self, node): self.newline(node) if isinstance (node.iter, Call) and node.iter.func.id == 'range': py_range_args = [ x.n if isinstance(x, Num) else self.dump_node(x) for x in node.iter.args ] if len(py_range_args) == 1: cpp_range_args = [0, py_range_args[0], 1] if len(py_range_args) == 2: cpp_range_args = [py_range_args[0], py_range_args[1], 1] if len(py_range_args) == 3: cpp_range_args = py_range_args self.write('for (') self.write_type() # default int self.visit(node.target) self.write('=%s; ' % cpp_range_args[0]) self.visit(node.target) if cpp_range_args[2] > 0: # if ascending self.write( '<%s; ' % cpp_range_args[1]) self.visit(node.target) if cpp_range_args[2] == 1: self.write('++ ') else: self.write('+=%s ' % cpp_range_args[2]) else: # if descending self.write( ' >%s; ' % cpp_range_args[1]) self.visit(node.target) if cpp_range_args[2] == -1: self.write('-- ') else: self.write('-=%s ' % -cpp_range_args[2]) self.write('){') else: thelist = node.iter # raw list if isinstance (thelist, List): # find (unused) name for list/array for arrname in "ABCDEFGHIJKLMNPRSTVWXZ": if not arrname in self.defined_variables: self.defined_variables[arrname] = thelist break self.write_type(thelist) self.write(arrname) self.write_dimension(thelist) self.write( ' = %s; ' % thelist.elts ) self.newline() looplen = len( thelist.elts ) # list name -- if we find name, then it should have been decleared earlier if isinstance (thelist, Name): arrname = thelist.id arrvalues = self.defined_variables.get(arrname, None ) looplen = '%s /*???*/' % len( arrvalues.elts if arrvalues else []) # ??? means warning -- as not sure if the current value is the last assigned to variable for loopvar in "ijkabcdxyzw": if not loopvar in self.defined_variables: self.defined_variables[loopvar] = None break self.varaible2indexed_substitutions[node.target] = "%s[%s]" % (arrname, loopvar); self.write('for (int @i=0; @i<@len; @i++){'.replace("@i", loopvar).replace('@len', str(looplen) ) ) self.newline() #~ self.write(' %s = %s;' % (node.target.id, self.varaible2indexed_substitutions[node.target]) ) self.write(' ') self.write('int ') # if node.target is simple variable -- most cases -- it should be declared self.visit(node.target) # might be expression or so # if it is -- what to do with definition? self.write(' = %s;' % ( self.varaible2indexed_substitutions[node.target]) ) self.body_or_else(node) self.newline(node); self.write('}') # finish block for cpp def visit_While(self, node): self.newline(node) self.write('while (') self.visit(node.test) self.write('){') self.body_or_else(node) self.newline(node); self.write('}') def visit_With(self, node): self.newline(node) self.write('with ') self.visit(node.context_expr) if node.optional_vars is not None: self.write(' as ') self.visit(node.optional_vars) self.write(': // !!!!!!!!!!!!!!!!!!!! ') # should manually change in other langs self.body(node.body) def visit_Pass(self, node): self.newline(node) self.write('pass') def visit_Print(self, node): # XXX: python 2.6 only #~ self.newline(node) self.visit_Print_call(node.values, node=node) def visit_Print_call(self, values, node=None, nl=True): self.newline(node) self.write('cout << ') want_comma = False for value in values: if want_comma: self.write(' << " " << ') self.visit(value) want_comma = True if nl: self.write(' << endl') self.write(';') def visit_Delete(self, node): self.newline(node) #~ self.write('del ') #TypeError: 'Delete' object is not iterable for idx, target in enumerate(node.targets): if idx: self.write(', ') self.visit(target) self.write(' = 0; /*???*/') def visit_TryExcept(self, node): self.newline(node) self.write('try:') self.body(node.body) for handler in node.handlers: self.visit(handler) def visit_TryFinally(self, node): self.newline(node) self.write('try:') self.body(node.body) self.newline(node) self.write('finally:') self.body(node.finalbody) def visit_Global(self, node): self.newline(node) self.write('global ' + ', '.join(node.names)) def visit_Nonlocal(self, node): self.newline(node) self.write('nonlocal ' + ', '.join(node.names)) def visit_Return(self, node): self.newline(node) self.write('return ') self.visit(node.value) self.write(';') def visit_Break(self, node): self.newline(node) self.write('break ;') def visit_Continue(self, node): self.newline(node) self.write('continue ;') def visit_Raise(self, node): # XXX: Python 2.6 / 3.0 compatibility self.newline(node) self.write('raise') if hasattr(node, 'exc') and node.exc is not None: self.write(' ') self.visit(node.exc) if node.cause is not None: self.write(' from ') self.visit(node.cause) elif hasattr(node, 'type') and node.type is not None: self.visit(node.type) if node.inst is not None: self.write(', ') self.visit(node.inst) if node.tback is not None: self.write(', ') self.visit(node.tback) # Expressions def visit_Attribute(self, node): self.visit(node.value) self.write('.' + node.attr) def visit_Call(self, node): want_comma = [] def write_comma(): if want_comma: self.write(', ') else: want_comma.append(True) process_normally = False if isinstance(node.func, Name) and node.func.id == 'print': self.visit_Print_call(values=node.args, node=node.func) elif isinstance(node.func, Name) and node.func.id == 'len': if isinstance(node.args[0], List): length = len( node.args[0].elts ) self.write( length ) elif isinstance(node.args[0], Name): arrvalues = self.defined_variables.get(node.args[0].id, None ) length = '%s /*???*/' % len( arrvalues.elts if arrvalues else []) # ??? means warning -- as not sure if the current value is the last assigned to variable self.write( length ) else: self.write( '/*???*/' ) process_normally = True else: process_normally = True if process_normally: self.visit(node.func) self.write('(') for arg in node.args: write_comma() self.visit(arg) for keyword in node.keywords: write_comma() self.write(keyword.arg + '=') self.visit(keyword.value) if node.starargs is not None: write_comma() self.write('*') self.visit(node.starargs) if node.kwargs is not None: write_comma() self.write('**') self.visit(node.kwargs) self.write(')') def visit_Name(self, node): self.write(node.id) def visit_Str(self, node): #~ if len(node.s) == 1: # char ?? #~ self.write(repr(node.s)) self.write(repr(node.s).replace("'", '"')) # double quote for string def visit_Bytes(self, node): self.write(repr(node.s)) def visit_Num(self, node): self.write(repr(node.n)) def visit_Tuple(self, node): self.write('(') idx = -1 for idx, item in enumerate(node.elts): if idx: self.write(', ') self.visit(item) self.write(idx and ')' or ',)') def sequence_visit(left, right): def visit(self, node): multidimentional = False #~ multidimentional_indent = len( self.result[-1] ) + 2 self.write(left) for idx, item in enumerate(node.elts): if idx: self.write(', ') if isinstance(item, List): # for matrix multidimentional = True self.newline(item); self.write(' '*17) self.visit(item) if multidimentional: self.newline(node); self.write(' '*14) self.write(right) return visit visit_List = sequence_visit('{', '}') #~ visit_Set = sequence_visit('{', '}') del sequence_visit def visit_Dict(self, node): self.write('{') for idx, (key, value) in enumerate(zip(node.keys, node.values)): if idx: self.write(', ') self.visit(key) self.write(': ') self.visit(value) self.write('}') def dump_opstack(self): #~ print(self.opstack) pass def visit_BinOp(self, node): if type(node.op) == Pow: self.write('pow(') self.visit(node.left) self.write(',') self.visit(node.right) self.write(')') else: if type(node.op) in [Add, Sub] and self.opstack: self.write('(') # TODO: decide when they are needed, when -- not... self.opstack.append(str(node.op)); self.dump_opstack() self.visit(node.left) #~ if type(node.op) == Div: # might need 1.0* in front to become double/float if type(node.op) == FloorDiv: self.write('/') # cpp doesn't have // else: self.write(' %s ' % BINOP_SYMBOLS[type(node.op)]) self.visit(node.right) del self.opstack[-1] if type(node.op) in [Add, Sub] and self.opstack: self.write(')') # TODO: decide when they are needed, when -- not... def visit_BoolOp(self, node): if type(node.op) == Or and self.opstack: self.write('(') self.opstack.append(str(node.op)); self.dump_opstack() for idx, value in enumerate(node.values): if idx: self.write(' %s ' % BOOLOP_SYMBOLS[type(node.op)]) self.visit(value) del self.opstack[-1] if type(node.op) == Or and self.opstack: self.write(')') def visit_Compare(self, node): if self.opstack: self.write('(') self.opstack.append('..'.join([str(op) for op in node.ops])); self.dump_opstack() self.visit(node.left) for op, right in zip(node.ops, node.comparators): self.write(' %s ' % CMPOP_SYMBOLS[type(op)]) self.visit(right) del self.opstack[-1] if self.opstack: self.write(')') def visit_UnaryOp(self, node): if self.opstack: self.write('(') self.opstack.append(str(node.op)); self.dump_opstack() op = UNARYOP_SYMBOLS[type(node.op)] self.write(op) if op == 'not': self.write(' ') self.visit(node.operand) del self.opstack[-1] if self.opstack: self.write(')') def visit_Subscript(self, node): self.visit(node.value) self.write('[') self.visit(node.slice) self.write(']') def visit_Slice(self, node): if node.lower is not None: self.visit(node.lower) self.write(':') if node.upper is not None: self.visit(node.upper) if node.step is not None: self.write(':') if not (isinstance(node.step, Name) and node.step.id == 'None'): self.visit(node.step) def visit_ExtSlice(self, node): for idx, item in node.dims: if idx: self.write(', ') self.visit(item) def visit_Yield(self, node): self.write('yield ') self.visit(node.value) def visit_Lambda(self, node): self.write('lambda ') self.signature(node.args) self.write(': ') self.visit(node.body) def visit_Ellipsis(self, node): self.write('Ellipsis') def generator_visit(left, right): def visit(self, node): self.write(left) self.visit(node.elt) for comprehension in node.generators: self.visit(comprehension) self.write(right) return visit visit_ListComp = generator_visit('[', ']') visit_GeneratorExp = generator_visit('(', ')') visit_SetComp = generator_visit('{', '}') del generator_visit def visit_DictComp(self, node): self.write('{') self.visit(node.key) self.write(': ') self.visit(node.value) for comprehension in node.generators: self.visit(comprehension) self.write('}') def visit_IfExp(self, node): self.visit(node.body) self.write(' if ') self.visit(node.test) self.write(' else ') self.visit(node.orelse) def visit_Starred(self, node): self.write('*') self.visit(node.value) def visit_Repr(self, node): # XXX: python 2.6 only self.write('`') self.visit(node.value) self.write('`') # Helper Nodes def visit_alias(self, node): self.write(node.name) if node.asname is not None: self.write(' as ' + node.asname) def visit_comprehension(self, node): self.write(' for ') self.visit(node.target) self.write(' in ') self.visit(node.iter) if node.ifs: for if_ in node.ifs: self.write(' if ') self.visit(if_) def visit_excepthandler(self, node): self.newline(node) self.write('except') if node.type is not None: self.write(' ') self.visit(node.type) if node.name is not None: self.write(' as ') self.visit(node.name) self.write(':') self.body(node.body)
[ [ 8, 0, 0.0106, 0.0174, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 1, 0, 0.0199, 0.0012, 0, 0.66, 0.0833, 809, 0, 1, 0, 0, 809, 0, 0 ], [ 14, 0, 0.0255, 0.005, 0, 0.66...
[ "\"\"\"\n codegen\n ~~~~~~~\n\n Extension to ast that allow ast -> CPP code generation.\n\n :copyright: Copyright 2008 by Armin Ronacher (adapted for C++ by Jurgis Pralgauskis)\n :license: BSD.", "from ast import *", "BOOLOP_SYMBOLS = {\n And: 'and', # &&\n Or: 'or' # ||\n}...
cat_sub_path='Testas-X' def set_cat_sub_path( new ): global cat_sub_path cat_sub_path = new __print_category("") def __print_category(cat_name): if cat_sub_path: cat_name = cat_sub_path+'/'+cat_name cat_name = cat_name.rstrip('/') print("\n\n$CATEGORY: $system$/%s\n" % cat_name ) try: from StringIO import StringIO except ImportError: from io import StringIO import sys class CaptureOut(list): #http://stackoverflow.com/a/16571630 def __enter__(self): self._stdout = sys.stdout sys.stdout = self._stringio = StringIO() return self def __exit__(self, *args): self.extend(self._stringio.getvalue().splitlines()) sys.stdout = self._stdout def generate_calls(**kwargs): def generated_calls(func): def func_wrapper(): if 'groups' in kwargs: groups = kwargs.pop('groups') else: groups = ["", len(list(kwargs.items())[0][1] ) ] # take the length of any group start = 0 # example: groups = ["less", 3, "equal", 0, "more", 3] -- take by pairs: for group, count in [ (groups[i:i+2]) for i in range(0, len(groups), 2)]: #print(group, count) if group or count>1: cat_name = func.__name__ if group: cat_name += "/"+group __print_category( cat_name ) # args for one call for k in range(start, start+count): args_instance = {argname:argvals[k] for argname, argvals in kwargs.items() } out = generate_question_by_call( func, name_extra=group, **args_instance ) ## print question start += count return func_wrapper return generated_calls #~ from helpers import src_to_GIFT import helpers import inspect import re #outfile = open('out.txt', 'w') def generate_question_by_call( func, name_extra="", **args_instance ): #~ print( func.__name__, args_instance ) ###### prepair Question def code_src(): # TODO - put in helpers #~ from pprint import pprint func_src = inspect.getsource(func) results = re.split( r'(def\s+{}[^:]+):'.format( func.__name__ ) , func_src, maxsplit=1) decorator, prototype, src = results for name, val in args_instance.items(): # inject actual arg values if name.startswith('_'): re_param = re.compile(r'\b%s\b'%name) src = re.sub(re_param, repr(val), src ) prototype = re.sub(re_param, repr(val), prototype ) return prototype, src prototype, src = code_src() prototype = prototype[len("def "):].strip(' \t') # get rid of word "def" if name_extra: prototype = prototype.replace(func.__name__, func.__name__+"__"+name_extra) question = (helpers.src_to_GIFT( prototype, # title #~ strip_first_line(src), helpers.code2pygmetshtml(src, 'py' , inlineCSS=True) ,# src #~ f_args, f_locals, CONVERT2CPP question_text="Ką atspausdins (atskirkite tarpais)?", markup_type="html", ) ) ###### prepair Answer # call the function with CaptureOut() as output: func( **args_instance ) answer = ' '.join( output ).rstrip('\n\t ') answer = "{=%s} " % helpers.escape_GIFT_spec_chars(answer) print ("\n\n" + question + answer ) return ("\n\n" + question + answer ) ################# def call_functions_by_decorators(fun_dict, outfile=None): import inspect decorated_functions = [x for x in fun_dict.values() if inspect.isfunction(x) and str(x).startswith('<function generate_calls.') ] Questions = [] for func in decorated_functions: with CaptureOut() as output: func() Questions.append( '\n'.join(output) ) for q in Questions: print("\n"*5, q) #~ print( q[200:]+"..."+q[:200] ) if outfile: with open(outfile, 'w', encoding="utf-8") as f: f.write(("\n"*5).join( Questions ) )
[ [ 14, 0, 0.0149, 0.0075, 0, 0.66, 0, 992, 1, 0, 0, 0, 0, 3, 0 ], [ 2, 0, 0.041, 0.0299, 0, 0.66, 0.0909, 380, 0, 1, 0, 0, 0, 0, 1 ], [ 14, 1, 0.0448, 0.0075, 1, 0.9...
[ "cat_sub_path='Testas-X'", "def set_cat_sub_path( new ):\n global cat_sub_path\n cat_sub_path = new\n __print_category(\"\")", " cat_sub_path = new", " __print_category(\"\")", "def __print_category(cat_name):\n if cat_sub_path: cat_name = cat_sub_path+'/'+cat_name\n cat_name = cat_nam...
#~ TYPE = "GIFT" #~ questions_file = "loops" #~ questions_file = "matrix" #~ questions_file = "functions" #~ questions_file = "variables_and_conditions" TYPE = "CLOZE" questions_file = "fill_missing_var_if_while_lists" #~ questions_file = "fill_missing_2_defs_morelists_dicts_etc" #~ questions_file = "fill_missing_tests" questions_file = 'Questions_tpl.' + questions_file CONVERT2CPP=False #~ CONVERT2CPP=True TRACE_STACK = False MENTION_UNGENERATED_QUESTIONS = False #~ import tokenize, trace import inspect from importlib import __import__ import sys import linecache import os.path import sys from io import StringIO import helpers call_level = 0 call_stack = [] return_stack = [] original_stdout = sys.stdout # keep a reference to STDOUT def start_catching_output(): sys.stdout = StringIO() def finish_catching_output(): #~ out = sys.stdout.getvalue() sys.stdout.close() sys.stdout = original_stdout def strip_first_line(src): return '\n'.join( src.split('\n')[1:] ) # http://docs.python.org/3/library/inspect.html # http://pymotw.com/2/sys/tracing.html def trace_calls(frame, event, arg): global call_level co = frame.f_code func_name = co.co_name if func_name.startswith('__')\ or func_name in ['<listcomp>']: return if func_name in ['write', '<module>']: # Ignore write() calls from print statements return func_line_no = frame.f_lineno func_fullfilename = co.co_filename func_modulename = frame.f_globals["__name__"] #~ if event == 'call': print("...", func_name) if not func_modulename in ['__main__', questions_file]: return # only trace calls in target file if event == 'call': #~ try: function = frame.f_globals[func_name] #~ except: return #~ print("$", co) #~ print("$", function) #~ print( ">>> ", inspect.getsourcefile(co) ) src = inspect.getsource(co) f_args, _, _, f_locals = inspect.getargvalues(frame) func_args = ','.join([repr(f_locals[arg]) for arg in f_args]) caller = frame.f_back caller_line_no = caller.f_lineno caller_filename = caller.f_code.co_filename # not precise... if call_level == 0: print() if TRACE_STACK: print ( '%s %s --> %s(%s) # %s' % (func_modulename, caller_line_no, func_name, func_args, linecache.getline(func_fullfilename, caller_line_no) ) # caller line ) if TYPE == "GIFT": print(helpers.src_to_GIFT( "%s(%s)" %( func_name, func_args ), # title strip_first_line(src), # src f_args, f_locals, CONVERT2CPP ) ) if TYPE == "CLOZE": global question_START question_START = helpers.src_to_CLOZE( "%s(%s)" %( func_name, func_args ), # title strip_first_line(src), # src f_args, f_locals, CONVERT2CPP, pygmentize=False ) if question_START: print(question_START) elif MENTION_UNGENERATED_QUESTIONS: print("<!-- no answers generated %s(%s) -->" %( func_name, func_args )) start_catching_output() call_level += 1 call_stack.append( dict(func_name=func_name, func_args=func_args, frame=frame) ) return trace_calls if event == 'return': call_level -= 1 last_called_func = call_stack.pop() #~ if call_level == 0: #~ if call_stack == []: result = str(arg) output = sys.stdout.getvalue() if TYPE == "GIFT": output = output.replace('\n', ' ').rstrip() output = helpers.escape_GIFT_spec_chars(output) #~ replace('#', '\#').replace('=', '\=').replace('~', '\~') result = output + ' ' + (str(arg if arg!=None else '') ) if last_called_func['frame'] == frame: return_stack.append( [func_name, "(%s)"% last_called_func['func_args'], '-->', arg, '>>>', output] ) if call_level == 0: finish_catching_output() if result.rstrip(' \n\t'): #~ print ("{=%s} # from %s" % (result.rstrip('\n'), func_name) ) if TYPE == "GIFT": print ("{=%s} " % result.rstrip('\n\t ') ) if TYPE == "CLOZE": if question_START: print( result ) # answers are already inside question... print( helpers.CLOZE_TPL_END ) else: print ("{=} \nWARNING: Empty result... NIEKO NEATSPAUSDINO") if TRACE_STACK: print ("\nRETURNS stack:") for x in return_stack: print( x ) del return_stack[:] return #TEST sys.settrace( trace_calls ) if TYPE == "GIFT": __import__( questions_file ) if TYPE == "CLOZE": print('<?xml version="1.0" encoding="UTF-8"?> <quiz>') __import__( questions_file ) print('</quiz>')
[ [ 14, 0, 0.0405, 0.0058, 0, 0.66, 0, 387, 1, 0, 0, 0, 0, 3, 0 ], [ 14, 0, 0.0462, 0.0058, 0, 0.66, 0.0417, 155, 1, 0, 0, 0, 0, 3, 0 ], [ 14, 0, 0.0694, 0.0058, 0, 0...
[ "TYPE = \"CLOZE\"", "questions_file = \"fill_missing_var_if_while_lists\"", "questions_file = 'Questions_tpl.' + questions_file", "CONVERT2CPP=False", "TRACE_STACK = False", "MENTION_UNGENERATED_QUESTIONS = False", "import inspect", "from importlib import __import__", "import sys", "import linecac...
import re import helpers import random import hashlib tpl = """#include <iostream> /*directives*/ using namespace std; /*functions*/ int main(){ /*code*/ return 0; } """ COMPILE = False with open('Questions_tpl/'+'questions_cpp_Errors.cpp') as f: examples = f.read() examples = examples.split('//') questions = [] answers = [] counter = 0 for ex in examples[1:]: title, code = ex.strip(' \t').split('\n', 1) #~ print(title, code) if ' ' in title: msg_type, explanation = title.strip(' \t').split(' ', 1) else: msg_type = title explanation = '' msg_types = {'ERR':'Error', 'WARN':'Warning', 'NOTICE':"Notice", "OK":"OK", 'SyntaxOK':'SyntaxOK'} answer = msg_types[msg_type] +": "+ explanation answer = answer.strip(' :') # check if same answer for different question if answer in answers: title += "_%s"%answers.count(answer) #~ print (title) answers.append(answer) #~ title = "CppErr_%s_"+str(len(answers)) + title ########## directives = [] # mostly includes for lineno, line in enumerate(code.split('\n')): if line.lstrip(' \t').startswith('#'): directives.append(line.lstrip(' \t')) if directives: etc, code = code.split(directives[-1]) # chop off directives (if found) directives = '\n'.join(directives) # join list to text ######### functions = '' if 'int main' in code: functions, code = re.split(r'int main.+\{', code, re.DOTALL) code = code[:code.rfind('}')] #remove closing '}' of main # dedent def dedent(line): return line[:4].lstrip(' ') + line[4:] code = '\n'.join( [dedent(line) for line in code.split('\n')]) if "/*main*/" in code: functions, code = code.split("/*main*/") code = code.rstrip('\n ') code = '\n'.join( [' '+line for line in code.split('\n')]) ######### full_code = tpl .replace('/*directives*/', directives)\ .replace('/*functions*/', functions)\ .replace('/*code*/', code) # remove multiple empty lines full_code = full_code.replace('\n \n', '\n\n') full_code = full_code.replace('\n \n', '\n\n') re_multiemptylines = re.compile(r'(\n\s*?)(\n\s*?)(\n *?)+', re.DOTALL) # somehow doesn't work --- http://regex.powertoy.org/ re_multiemptylines = re.compile(r'\n\n\n+', re.DOTALL) full_code = re_multiemptylines.sub('\n\n', full_code) ################## counter += 1 m = hashlib.md5() m.update(title.encode('utf8')) question = helpers.src_to_GIFT( title, full_code, question_text='Ar/kokia čia yra bėda?', lang_code2img='cpp', title_without_hints= "Err_"+m.hexdigest()#"Err_%s" %counter ) questions.append(question) #~ print("\n\n********", title, '\n\n', full_code) #~ print(question) if COMPILE: #~ if True: with open('/tmp/a.cpp', 'w' ) as f: f.write(full_code) print ('\n\n', full_code) print('-----------------') import subprocess out_txt = subprocess.getoutput('g++ -Wall -c /tmp/a.cpp') print("---- Compilation output: --------\n", out_txt) #~ try: #~ out_txt = subprocess.check_output( #~ ['g++', '-Wall', '-c', '/tmp/a.cpp'], #~ stderr=subprocess.STDOUT, #~ universal_newlines=True #~ ) #~ except subprocess.CalledProcessError as e: #(retcode, cmd, output=output) #~ print("output", e.output) ## Output stufff print("\n$CATEGORY: $system$/CPP/ERRORS_2\n") for q, a in zip(questions, answers[:]): print('\n\n') print( q ) print('{') random.shuffle(answers) how_many_choices = random.randint(4, min(len(answers), 8)) # at least 4 choices for choice in sorted(list(set(answers[:how_many_choices] + [a, 'OK']))): print( ' ', '=' if a==choice else '~', helpers.escape_GIFT_spec_chars(choice) ) print('}') #~ print (len(questions))
[ [ 1, 0, 0.0069, 0.0069, 0, 0.66, 0, 540, 0, 1, 0, 0, 540, 0, 0 ], [ 1, 0, 0.0139, 0.0069, 0, 0.66, 0.0833, 510, 0, 1, 0, 0, 510, 0, 0 ], [ 1, 0, 0.0208, 0.0069, 0, ...
[ "import re", "import helpers", "import random", "import hashlib", "tpl = \"\"\"#include <iostream>\n/*directives*/\n\nusing namespace std;\n\n/*functions*/\n\nint main(){", "COMPILE = False", " examples = f.read()", "examples = examples.split('//')", "questions = []", "answers = []", "counter...
import re import os import helpers #~ TASK = 'py2cpp' #can convert: py2img, cpp2img, py2cpp #~ TASK = 'cpp2img' #can convert: py2cpp, py2img, cpp2img, *2img TASK = 'cpp2img' #~ NAME_SEARCH = '' NAME_SEARCH = 'nonrandom' LINENOS4IMG = False html_entities = { '&quot;': '"', '&amp;': '&', '&nbsp;': ' ', } html_entities_more_less ={ '&gt;': '>', '&lt;': '<', } html_entities.update( html_entities_more_less ) def html2txt(html): txt = html txt = txt.replace(' ', ' ') # replace mystical whitespace char with real space :) txt = txt.replace('<br />', '\n') re_short_tag = r'</?(b|i|u|p|span|div|pre|a|strong|font)\b[^<]{0,50}?>' # TODO: WARNING -- needs to find only real tags re_long_tag = r'</?(p|span|div|pre)\b[^<]*?>' # TODO: WARNING -- needs to find only real tags txt = re.sub(re_short_tag, '', txt) # flags=re.DOTALL - better not use DOTALL here -- as < lt gt > signs might occur in different lines like: "5<b ... a>8"... txt = re.sub(re_long_tag, '', txt) for entity, symbol in html_entities.items(): txt = txt.replace(entity, symbol) #~ re_multiple_empty_lines = r'(\n(\s*)){3, 10}' re_multiple_empty_lines = r'\n{3,10}' txt = re.sub(re_multiple_empty_lines, '\n\n', txt, flags=re.DOTALL ) return txt def code2html_entities(txt): for entity, symbol in html_entities_more_less.items(): txt = txt.replace(symbol, entity) return txt #~ xmldir = 'output/Moodle/xml/nonrandom/' #~ xmldir = 'output/Moodle/xml/_py2cpp/' counter = 0 xmldir = 'output/Moodle/xml/' for x in os.listdir( xmldir ): srclang = TASK.split('2')[0] if not x.startswith(srclang): continue if NAME_SEARCH: # if filter by name fragment is defined if not NAME_SEARCH in x: # and it is not found continue # skip if x.endswith('.xml') and not x.endswith('.xmlNEW.xml'): print(x) #~ if x.endswith("cpp-klausimai-Kintamieji_Salyga_Ciklas-20131112-0815.xml"): #~ if x.endswith("klausimai-Funkcijos-20131112-0845.xml"): #~ if x.endswith("klausimai-TFKTPROGRAM1-Programos sekimas-20131112-0812.xml"): xmlfilename = x topic = xmlfilename.split('-', 2)[1] xml = open(xmldir + xmlfilename).read() re_question_typeonly_tpl = r'<question type="(.*?)">.*?</question>' re_name_tpl = r'<name>\s*<text>(.*?)</text>\s*</name>' re_questiontext_tpl = r'<questiontext format="(.*?)">\s*<text>(.*?)</text>\s*</questiontext>' re_question_details_tpl = r'<question type="(.*?)">.*?'+re_name_tpl+r'.*?'+re_questiontext_tpl+r'.*?</question>' #~ print( re_question_details_tpl ) re_question_typeonly = re.compile(re_question_typeonly_tpl, re.DOTALL) re_question_details = re.compile(re_question_details_tpl, re.DOTALL) newxml = xml names=[] category = None for match_typeonly in re_question_typeonly.finditer(xml, re.DOTALL): questiontype = match_typeonly.group(1) question = match_typeonly.group(0) #~ print("||| ", question , " |||") if questiontype == 'category': category = question.split("<text>")[1].split("</text>")[0] print("\n== CATEGORY == ", category.split('/')[-1]) continue if questiontype in ['calculated', 'shortanswer', 'multichoice', 'numerical']: # calculated might be a mess #~ if questiontype in ['calculated']: # calculated might be a mess match_details = re_question_details.match(question) questiontype, name, textformat, text = match_details.groups() if text.startswith('<![CDATA['): text = text[len('<![CDATA['):-len(']]>')] else: newxml = newxml.replace(text, '<![CDATA['+text+']]>') intro, code, html = None, text, None code_original = '' print("\n\n###", helpers.escape_path(name), questiontype, textformat, #~ "\n-------------\n", text, #~ "\n----------------------\n", code, #~ "\n----------------------\n", html ) names.append(name) if textformat == 'html': if text.startswith('<p>') and text.endswith('</p>'): text = text[len('<p>'):-len('</p>')] #~ if text.count("</p>") > 1: #~ print("WARNING", name, ": many <p> - migt cause trouble") #~ if text.count("</p>") > 0: #~ re_p = re.compile(r"<p ?.*?>(.*?)</p>", re.DOTALL) #~ match = re_match(text) #~ if match: #~ text = match.group(1) if questiontype == 'calculated': # find placeholders {a} {b} {c} ... lines = text.split('<br />') lastline_defined_value = -1 # for Python should be ok, for C++ not for nr, line in enumerate(lines): #~ has_defined_value = False for a in 'abc': if '{'+a+'}' in line: lastline_defined_value = nr if lastline_defined_value != -1: intro = '<br />'.join(lines[:lastline_defined_value+1]) + '<br />' code = '<br />'.join(lines[lastline_defined_value+1:]) else: intro, code = '', text code_original = code code = html2txt(code) else: intro, code = '', text if '<pre' in text: re_prehtml=re.compile(r"(.*?)<pre.*?>(.*?)</pre>", re.DOTALL) match = re_prehtml.search(text) if match: intro = match.group(1) code = match.group(2) code_original = code code = html2txt(code) else: #~ # and strip other tags? if '?' in text: intro, code = text.split("?", 1) intro += "?" if '<br />' in code: intro2, code = code.split('<br />', 1) intro += intro2 + '<br />' elif '<br />' in text: intro, code = text.split('<br />', 1) intro += '<br />' code_original = code code = html2txt(code) #~ print( "code ", code ) #~ print( "code_original ", code_original ) if textformat == 'markdown': if "?" in text: intro, code = text.split("?", 1) # expects ? linebreaks before code intro += "?" if '\n' in code: intro_end, code = code.split('\n', 1) intro += intro_end+'\n' elif "\n" in text: intro, code = text.split("\n", 1) # expects (two) linebreaks before code if code_original or code: if TASK=='py2cpp': import py2cpp print( code, "\n----------------------\n") translated_code = py2cpp.convert( code ) print(translated_code , "\n----------------------\n") if textformat == 'html': #~ translated_code = code2html_entities(translated_code) translated_code = "<pre>\n%s\n</pre>" % translated_code newxml = newxml.replace(code_original or code, translated_code) if '2img' in TASK: lang=TASK[:-len('2img')] #~ counter+=1 #~ name_without_hints="Errors_%"% counter, helpers.code_highlight( name, lang=lang, code=code, LINENOS4IMG=LINENOS4IMG, ) # insert link to image if textformat in ('html', 'markdown'): newxml = newxml.replace( code_original or code, helpers.img_placer(textformat, img_name=lang+'_'+name) ) langNames = dict(py="Python", cpp="C++", java="Java", php="PHP") category_trunk = '$system$/%s/' % langNames[srclang] #like: $system$/Python/.... if not category_trunk in newxml: category_trunk = '$system$/' # just newxml = newxml.replace(category_trunk, category_trunk+TASK.upper()+'/' ) if 'nonrandom' in xmldir: xmldir = xmldir.replace('/nonrandom', '') xmlfilename = 'nonrandom-' + xmlfilename if TASK.endswith('2img'): # convert to img with open(xmldir + '_code2img/' + xmlfilename+"NEW.xml", 'w') as f: f.write(newxml) else: # translate to other lang targetlang = TASK.split('2')[1] prefix = '_'+TASK+'/'+targetlang+'-'+TASK + '-' with open(xmldir + prefix + xmlfilename, 'w') as f: f.write(newxml) ############## phantomjs code # https://github.com/ariya/phantomjs/blob/master/examples/render_multi_url.js # https://github.com/ariya/phantomjs/blob/master/examples/scandir.js # http://www.cambus.net/creating-thumbnails-using-phantomjs-and-imagemagick/ # http://phantomjs.org/screen-capture.html # http://www.kobashicomputing.com/a-look-at-phantomjs #~ current_dir = os.path.dirname(os.path.realpath(__file__)) #~ tpl = """ #~ var pageNR = require('webpage').create(); #~ pageNR.open('PATH', function() { #~ pageNR.render('NAME.png'); #~ phantom.exit(); #~ }); #~ """ #~ js_code = "" #~ for name in names: #~ js
[ [ 1, 0, 0.0039, 0.0039, 0, 0.66, 0, 540, 0, 1, 0, 0, 540, 0, 0 ], [ 1, 0, 0.0079, 0.0039, 0, 0.66, 0.0769, 688, 0, 1, 0, 0, 688, 0, 0 ], [ 1, 0, 0.0118, 0.0039, 0, ...
[ "import re", "import os", "import helpers", "TASK = 'cpp2img'", "NAME_SEARCH = 'nonrandom'", "LINENOS4IMG = False", "html_entities = {\n '&quot;': '\"',\n '&amp;': '&',\n '&nbsp;': ' ',\n}", "html_entities_more_less ={\n '&gt;': '>',\n '&lt;': '<',\n}", "html_entities.update( html_ent...
try: from tpl_helpers import __rand_questions, __print_category except ImportError: from .tpl_helpers import __rand_questions, __print_category def Loop_C( _list=[2, 8, 4, 6, 9, 0, 1] ): # {=%(track['S`1'])s} S = 0 # >>>S`0 n = 0 for x in _list: n = n + 1; S = S + x; print(S) # >>>S`1 if x > S/n: S = S / 2; print(S) # >>>S`2 Loop_C() def Loop_pseudomax(_list=[2, 8, 4, 6, 9, 0, 1]): previous = 0 for x in _list: if x > previous: print( x ) previous = x def ListFilter(_info = [5, 8, 3, 2, 10]): """What will be printed?""" for x in _info: if x > 5: print( x, end=" " ) ListFilter() def ListConditionalCount( _info=[5, 1, 3, 2, 5] ): """What will be printed?""" counter = 0 for x in _info: counter += 1 if x > counter: print( x, counter, end=" " ) def ListFindMin(_info = [5, 8, 3, 2, 10]): """What will be printed?""" min = 1000 for x in _info: if x < min: min = x print( x, end=" " ) ListFindMin()
[ [ 7, 0, 0.05, 0.08, 0, 0.66, 0, 0, 0, 1, 0, 0, 0, 0, 0 ], [ 1, 1, 0.04, 0.02, 1, 0.85, 0, 125, 0, 2, 0, 0, 125, 0, 0 ], [ 1, 1, 0.08, 0.02, 1, 0.85, 0, 125,...
[ "try:\n from tpl_helpers import __rand_questions, __print_category\nexcept ImportError:\n from .tpl_helpers import __rand_questions, __print_category", " from tpl_helpers import __rand_questions, __print_category", " from .tpl_helpers import __rand_questions, __print_category", "def Loop_C( _list=...
import tpl_helpers # calls parent_dir_2path() -- to let imports from generate_via_decorators import generate_calls, set_cat_sub_path, call_functions_by_decorators @generate_calls( #_pinigai = [-10, 0, 1, 5, 9] , #groups = ["less", 1, "equal", 1, "more", 3] , _pinigai = [-10, -7, -2, 0, 0.5, 9] , groups = ["less", 3, "equal", 1, "more", 2] , ) def ifMoreLess0_noEqual( _pinigai ): pinigai = _pinigai if pinigai > 0: print( "Turim", pinigai ) if pinigai < 0: print( "Skoloj", -pinigai) print("Eur") @generate_calls( _pinigai = [17, 15, 10, 10, 15, 15, 10, 12, ], ## randint(10, 20) _kebabas = [10, 3, 6, 8, 2, 8, 6, 8, ], ## randint(2, 10) _sokoladas = [ 1, 2, 4, 1, 3, 1, 4, 5, ], ## randint(1, 5) _valanda = [10, 8, 12, 14, 15, 17, 22, 16, ], groups = ["nieko", 2, "dali", 3, "visus", 3 ], ) def pinigu_leidimas(_pinigai, _kebabas, _sokoladas, _valanda): pinigai = _pinigai kebabas = _kebabas sokoladas = _sokoladas valanda = _valanda print( "buvo", pinigai ) if valanda >= 12: # laikas pietums pinigai = pinigai - kebabas if valanda > 15: # laikas pavakariams pinigai = pinigai - sokoladas print( "liko", pinigai ) ##################################################################################### if __name__=="__main__": set_cat_sub_path( "NG: Variables and Conditions" ) def name_by_file(tag='.GIFT.txt'): import inspect return inspect.getfile(inspect.currentframe()) [:-len('.py')] + tag call_functions_by_decorators(fun_dict=globals(), outfile='out_generated/'+name_by_file() ) """ *** def ifMore(): taskai = 15 if taskai > 10: # if > : pergale = True print(pergale) *** if vidurkis < 4: print("prastai") else: print("normaliai") *** vardas = input("Kas tu?") amzius = int( input("Kiek tau metų?") ) print( vardas, "gimė prieš", amzius, "metų.") *** preke = "duona" kaina = 2.5 print( preke, "kainuoja", kaina, "Lt" ) *** """
[ [ 1, 0, 0.0112, 0.0112, 0, 0.66, 0, 125, 0, 1, 0, 0, 125, 0, 0 ], [ 1, 0, 0.0225, 0.0112, 0, 0.66, 0.2, 246, 0, 3, 0, 0, 246, 0, 0 ], [ 2, 0, 0.1461, 0.0787, 0, 0.6...
[ "import tpl_helpers # calls parent_dir_2path() -- to let imports", "from generate_via_decorators import generate_calls, set_cat_sub_path, call_functions_by_decorators", "def ifMoreLess0_noEqual( _pinigai ): \n pinigai = _pinigai \n if pinigai > 0:\n print( \"Turim\", pinigai )\n if pinigai <...
try: from tpl_helpers import __rand_questions, __print_category except ImportError: from .tpl_helpers import __rand_questions, __print_category from random import randint as rint, choice # ********************************** __print_category('Variables and Conditions', sub_path="FillGaps", _type="CLOZE") ############ Arithmetics ######### def Arithmetics_simple1(__HIDE='', _a=5, _b=2, _c=4): x = _a * _b - _c # HIDE(__HIDE) print (x) for s in '= x * _b -_c'.split(): Arithmetics_simple1(__HIDE=s, _a=rint( 5, 7), _b=rint(2, 3), _c=rint(1, 4)) def Arithmetics_simple2(__H='', _a=20, _b=2, _c=4): x = _a - _c y = _a + x * _b # HIDE(__H) print (x, y) for s in '= x +x x*'.split(): Arithmetics_simple2(__H=s, _a=rint( 15, 20), _b=rint(2, 3), _c=rint(1, 4)) def Arithmetics_simple21(_a=20, _b=2, _c=4): x = _a - _c y = _a + x * _b # HIDE(=) HIDE(+) HIDE(*) print (x, y) Arithmetics_simple21() def Arithmetics_simple3( __HIDE='', _a=5, _b=2, _c=4): a = _a # HIDE(a=) b = _b # HIDE(b=) x = a - _c * b print (x) Arithmetics_simple3() ############ Variables ######### def Var_Arithmetic_PlusMult(_a=2, _b=5, _c=3): # {=%(track['x'])s} x = _a x = x + _b # HIDE(+_b) print(x) # HIDE(print) x = _c * x # HIDE(*) print(x) Var_Arithmetic_PlusMult() def Variables_simple1(_a=20, _b=6): pinigai = _a # HIDE(pinigai) kebabas = _b pinigai = pinigai - kebabas # kintamojo pakeitimas HIDE(pinigai) print (pinigai) Variables_simple1() def Variables_simple2(_a=20, _b=6): """Kiek nupirks porcijų ir kiek liks pinigų?""" pinigai = _a # pradinė piginų suma kebabas = _b # kebabo kaina HIDE(kebabas) HIDE(_a) porcijos = pinigai // kebabas # suapvalinanti (žemyn) dalyba HIDE(porcijos) pinigai = pinigai - porcijos*kebabas # likutis HIDE(pinigai) print (porcijos, pinigai) Variables_simple2() def Variables_and_IF1(_a=20, _b=3, _c=4): """Kiek nupirks porcijų ir kiek liks pinigų?""" pinigai = _a # pradinė piginų suma kebabas = _b # kebabo kaina draugai = _c porcijos = pinigai // kebabas # suapvalinanti (žemyn) dalyba "//" print("Galima nupirkti", porcijos, "kebabus") if porcijos > draugai+1: # HIDE(>) porcijos = draugai+1 # užteks man ir draugams po porciją # HIDE(+1) islaidos = porcijos * kebabas # HIDE(*) pinigai = pinigai - islaidos print (porcijos, pinigai) Variables_and_IF1() # ********************************** __print_category('While', sub_path="FillGaps/Loops", _type="CLOZE") def While1(_a=0, _b=2, _c=10): x = _a while x < _c: # HIDE(x<) print(x) x = x + _b # HIDE(x=x) While1() def While2(_a=0, _b=2, _c=10): x = _c while x > _a: # HIDE(while) print(x) # HIDE(print) x = x - _b # HIDE( =) HIDE(-) While2() # ********************************** __print_category('Lists', sub_path="FillGaps/Loops", _type="CLOZE") def List1_filtravimas(): Pazymiai = [10, 5, 2] # HIDE(5) kontrolinis = 5 # HIDE( kontrolinis ) Pazymiai.append( kontrolinis ) # HIDE(append) for x in Pazymiai: if x > kontrolinis: # HIDE( if ) HIDE(>) print("buvo geriau") elif x < kontrolinis: # HIDE( < ) HIDE(:) print("buvo blogiau") else: # HIDE(else) print("nieko naujo") List1_filtravimas() def List2_vidurkis(): Pazymiai = [10, 5, 2] suma = 0 for x in Pazymiai: # HIDE(for) HIDE(in) suma = suma + x # HIDE(suma+) print("pridėjus", x, "turim", suma) print("Pažymių kiekis:", len(Pazymiai)) print ("Vidurkis yra", suma/len(Pazymiai) ) # HIDE(suma) List2_vidurkis() def List3_du_sar_mumizmatika(): Petro_monetos = [10, 5, 20] Jono_monetos = [2, 10, 1, 50, 5] Bendros_monetos = [] for m in Jono_monetos: # HIDE(for) HIDE(in) print(m) # HIDE(m) for m in Petro_monetos: # HIDE(for) if m in Jono_monetos: # HIDE(Jono) print(m, "jau buvo") else: print(m) List3_du_sar_mumizmatika() def List4_ar_yra_sarase(): Pazymiai = [10, 5, 2] #HIDEEXACT([) HIDEEXACT(]) naujas = 5 # HIDE(=) if naujas in Pazymiai: # HIDE(if) print("ir vėl gavai", naujas) List4_ar_yra_sarase()
[ [ 7, 0, 0.0153, 0.0245, 0, 0.66, 0, 0, 0, 1, 0, 0, 0, 0, 0 ], [ 1, 1, 0.0123, 0.0061, 1, 0.48, 0, 125, 0, 2, 0, 0, 125, 0, 0 ], [ 1, 1, 0.0245, 0.0061, 1, 0.48, ...
[ "try:\n from tpl_helpers import __rand_questions, __print_category\nexcept ImportError:\n from .tpl_helpers import __rand_questions, __print_category", " from tpl_helpers import __rand_questions, __print_category", " from .tpl_helpers import __rand_questions, __print_category", "from random import...
from random import randint #~ from helpers import * #~ __print_category('FUNCTIONS') def __rand_questions(fun, args_intervals, how_many): __print_category(fun.__name__+'_RANDOM') for i in range(how_many): args = [randint(*interval) for interval in args_intervals] fun( *args ) def __print_category(cat_name, sub_path='TESTAI/Funkcijos/Unary_Arithmetic'): print("\n$CATEGORY: $system$/%s/%s\n" % (sub_path, cat_name)) ########## unary arithmetic returns ########## def funCalls_print_inside_G_FGF(_a=-3, _k=10): """Ką atspausdins? (atskirkite tarpais)""" def abra(x): return x*2 def kad(y): print (y) return y+_k abra( kad( abra (_a) ) ) __rand_questions(funCalls_print_inside_G_FGF, [(-3, 9), (-3, 9)], 5 ) def funCalls_print_inside_both_FGF(_a=-3, _k=10): """Ką atspausdins? (atskirkite tarpais)""" def abra(x): print( x ) return x*2 def kad(y): print (y) return y+_k abra( kad( abra (_a) ) ) __rand_questions(funCalls_print_inside_both_FGF, [(-3, 9), (-3, 9)], 5 ) def funCalls_FGF(_a=-3, _k=10): """Ką atspausdins?""" def abra(x): return x*3 def kad(y): return y+_k print( abra( kad( abra (_a) ) ) ) __rand_questions(funCalls_FGF, [(-3, 9), (-3, 9)], 5 ) def funCalls_FG(_a=-3, _k=10): """Ką atspausdins?""" def abra(x): return x*5 def kad(y): return y+_k print( kad( abra (_a) ) ) __rand_questions(funCalls_FG, [(-3, 9), (-3, 9)], 5 ) def funCalls_unreached_print_inside_FG(_a=-3, _k=10): """Ką atspausdins? (atskirkite tarpais)""" def abra(x): return x*2 def kad(y): return y+_k print (y) print( kad( abra (_a) ) ) __rand_questions(funCalls_unreached_print_inside_FG, [(-3, 9), (-3, 9)], 5 ) def __print_category(cat_name, sub_path='TESTAI/Funkcijos/Binary_arithmetic'): print("\n$CATEGORY: $system$/%s/%s\n" % (sub_path, cat_name)) ############ binary arguments ###### def funCalls_FG_2(_a=-3, _b=2, _k=10): """Ką atspausdins? (atskirkite tarpais)""" def abra(x, y): return x*y def kad(y): return y+_k print( kad( abra (_a, _b) ) ) __rand_questions(funCalls_FG_2, [(-3, 9), (-3, 9), (-3, 9)], 5 ) def funCalls_print_inside_G_FGF_2(_a=-3, _b=2, _k=10): """Ką atspausdins? (atskirkite tarpais)""" def abra(x, y): return x*y def kad(y): print (y) return y+_k print( abra( _b, kad( abra (_a, _b+1) ) ) ) __rand_questions(funCalls_print_inside_G_FGF_2, [(-3, 9), (-3, 9), (-3, 9)], 5 ) def funCalls_FGF_2(_a=-3, _b=2, _k=10): """Ką atspausdins?""" def abra(x, z): return x*z def kad(y): return y+_k print( abra( _a, kad( abra (_a, _b) ) ) ) __rand_questions(funCalls_FGF_2, [(-3, 9), (-3, 9), (-3, 9)], 5 ) ######## Various ############## def __print_category(cat_name, sub_path='TESTAI/Funkcijos/Various'): print("\n$CATEGORY: $system$/%s/%s\n" % (sub_path, cat_name)) ########## if/else returns ########## def fun_ifs_stacked(_a=8, _b=7, _min=4): """Ką atspausdins?""" def stipendija(x, riba): if x < _min: return -100 if x >= riba: return 50*x return 0 print( stipendija(_a, _b) ) __rand_questions(fun_ifs_stacked, [(2, 10), (2, 9), (0, 8)], 5 ) __print_category('fun_loops_FIXED') ###### loops in functions ########## ######### loop sum ######## def fun_loop_sum_print_inside(_sar=[8, 5, 2]): """Ką atspausdins?""" def sumuojam( sar ): suma = 0 for x in sar: suma = suma+x print ( suma ) return suma print( sumuojam(_sar) ) fun_loop_sum_print_inside() def fun_loop_sum_early_return(_sar=[7, 2, 3]): """Ką atspausdins?""" def sumuojam( sar ): suma = 0 for x in sar: suma = suma+x return suma print( sumuojam(_sar) ) fun_loop_sum_early_return() def fun_loop_sum(_sar=[-7, 2, 3]): """Ką atspausdins?""" def sumuojam( sar ): suma = 0 for x in sar: suma = suma+x return suma print( sumuojam(_sar) ) fun_loop_sum() def fun_loop_sum__avg(_sar=[10, 2, 3]): """Ką atspausdins?""" def sumuojam( sar ): suma = 0 for x in sar: suma = suma+x return suma sar = _sar vid = sumuojam(sar) / len(sar) print(vid) fun_loop_sum__avg() ####### loop filters ##### def fun_loop_print_filter_remainder(_sar=[9, 2, 3, 12, 10], _dalmuo=3): """Ką atspausdins?""" def filtruok_skaicius( sar ): for x in sar: if x % _dalmuo == 0: # jeigu dalijasi be liekanos print (x) filtruok_skaicius( _sar ) fun_loop_print_filter_remainder() def fun_loop_print_sum_filter(_sar=[4, 2, 2, 5, 4, 5], _k=3): """Ką atspausdins?""" def filtruok_skaicius( sar ): suma = 0 for x in sar: suma = suma+x if suma / x > _k: print (x) filtruok_skaicius( _sar ) fun_loop_print_sum_filter() ####### lists #########
[ [ 1, 0, 0.0086, 0.0043, 0, 0.66, 0, 715, 0, 1, 0, 0, 715, 0, 0 ], [ 2, 0, 0.0386, 0.0215, 0, 0.66, 0.0286, 325, 0, 3, 0, 0, 0, 0, 4 ], [ 8, 1, 0.0343, 0.0043, 1, 0....
[ "from random import randint", "def __rand_questions(fun, args_intervals, how_many):\n __print_category(fun.__name__+'_RANDOM')\n for i in range(how_many):\n args = [randint(*interval) for interval in args_intervals]\n fun( *args )", " __print_category(fun.__name__+'_RANDOM')", " for...
from random import randint, choice #~ from helpers import * #~ __print_category('FUNCTIONS') def __rand_questions(fun, args_intervals, how_many): __print_category(fun.__name__+'_RANDOM') for i in range(how_many): args = [randint(*interval) for interval in args_intervals] fun( *args ) import copy def __randchoice_questions(fun, args_options_lists, how_many): __print_category(fun.__name__+'_RANDOM') for i in range(how_many): args = [choice(copy.deepcopy(options_list)) for options_list in args_options_lists] fun( *args ) def __print_category(cat_name, sub_path='TESTAI/Matrix'): print("\n$CATEGORY: $system$/%s/%s\n" % (sub_path, cat_name)) ##############################Ęę # # Choices data # ############################### rows_len3 = [ [5, 6, 2], [4, 3, 1], [8, 2, 4], [9, 0, 5], [6, 6, 6], [7, 2, 13], ] rows_len4= [ [8, 10, -2, 5], [5, 3, 1, 0], [10, 2, 5, 3], [4, 9, 0, 3], [6, 7, 7, 7], [2, 2, 10, 5], [1, 2, 1, 2], [4, 7, 5, 6], ] rows_len5= [ [3, 10, 2, 0, 5], [2, 8, 1, 5, 3], [4, 2, 3, 10, 5], [11, 1, 53, 0, 8], [8, 9, 3, 2, 1], [8, 3, 2, 1, 5], ] ################################# ################################# # # SQUARE MATRIX 3x3 # ################################# ################################# ################ def M3x3_print_nthRow_mthCol( _n=2, _m=0, _e1=[2, 3, 1], _e2=[4, 3, 0], _e3=[5, 2, 8] ): """Ką atspausdins? (atskirkite tarpais)""" M = [ _e1, _e2, _e3, ] print( M[_n][_m] ) __randchoice_questions(M3x3_print_nthRow_mthCol, [ range(3), range(3), rows_len3, rows_len3, rows_len3 ], 5 ) def M3x3_print_Col(_cnr=0, _e1=[5, 6, 2], _e2=[4, 3, 0], _e3=[5, 2, 8] ): """Ką atspausdins? (atskirkite tarpais)""" M = [ _e1, _e2, _e3, ] for k in range(3): print( M[k][_cnr] ) __randchoice_questions(M3x3_print_Col, [range(3), rows_len3, rows_len3, rows_len3 ], 5 ) ################ def M3x3_print_Diagonal(_e1=[5, 6, 2], _e2=[4, 3, 0], _e3=[5, 2, 8] ): """Ką atspausdins? (atskirkite tarpais)""" M = [ _e1, _e2, _e3, ] for k in [0, 1, 2]: print( M[k][k] ) __randchoice_questions(M3x3_print_Diagonal, [ rows_len3, rows_len3, rows_len3 ], 5 ) ################ def M3x3_print_nthElement_by0th( _e1=[2, 3, 1], _e2=[4, 3, 0], _e3=[5, 2, 8] ): """Ką atspausdins? (atskirkite tarpais)""" M = [ _e1, _e2, _e3, ] for k in range(3): n = M[k][0] // 2 # padalinus suapvalina žemyn if n < len( M[k] ): print( M[k][n] ) __randchoice_questions(M3x3_print_nthElement_by0th, [ rows_len3, rows_len3, rows_len3 ], 5 ) ################ def M3x3_print_diffs_sameEls_1stRowCol( _e1=[2, 3, 1], _e2=[4, 3, 0], _e3=[5, 2, 8] ): """Ką atspausdins? (atskirkite tarpais)""" M = [ _e1, _e2, _e3, ] for k in range(3): print( M[k][0] - M[0][k] ) __randchoice_questions(M3x3_print_diffs_sameEls_1stRowCol, [ rows_len3, rows_len3, rows_len3 ], 5 ) ################ def M3x3_print_diffs_sameEls_nthRow_mthCol( _n=2, _m=0, _e1=[2, 3, 1], _e2=[4, 3, 0], _e3=[5, 2, 8] ): """Ką atspausdins? (atskirkite tarpais)""" M = [ _e1, _e2, _e3, ] n = len(M) for k in range(n): print( M[k][_m] - M[_n][k] ) __randchoice_questions(M3x3_print_diffs_sameEls_nthRow_mthCol, [ range(3), range(3), rows_len3, rows_len3, rows_len3 ], 5 ) ################ def M3x3_print_row_sums( _e1=[2, 3, 1], _e2=[4, 3, 0], _e3=[5, 2, 8] ): """Ką atspausdins? (atskirkite tarpais)""" M = [ _e1, _e2, _e3, ] for row in M: print(sum(row) ) __randchoice_questions(M3x3_print_row_sums, [ rows_len3, rows_len3, rows_len3 ], 5 ) ################ def M3x3_print_row_sums_with_indices( _e1=[2, 3, 1], _e2=[4, 3, 0], _e3=[5, 2, 8] ): """Ką atspausdins? (atskirkite tarpais)""" M = [ _e1, _e2, _e3, ] n = len(M) for k in range(n): print(k, sum(M[k]) ) __randchoice_questions(M3x3_print_row_sums, [ rows_len3, rows_len3, rows_len3 ], 5 ) ################ def M3x3_del_diagonal_and_print_sums( _e1=[2, 3, 1], _e2=[4, 3, 0], _e3=[5, 2, 8] ): """Ką atspausdins? (atskirkite tarpais)""" M = [ _e1, _e2, _e3, ] n = len(M) for k in range(n): del M[k][k] print( sum(M[k]) ) __randchoice_questions(M3x3_del_diagonal_and_print_sums, [ rows_len3[:], rows_len3[:], rows_len3[:] ], 5 ) ################ HARD def M3x3_del_by_0thRowEls_HARD( _e1=[2, 3, 1], _e2=[4, 3, 0], _e3=[5, 2, 8] ): """Ką atspausdins? (atskirkite tarpais)""" M = [ _e1, _e2, _e3, ] for k in range(3): a = M[0][k] if a < len( M ): del M[k][a] print( sum( M[k] ) ) __randchoice_questions(M3x3_del_by_0thRowEls_HARD, [ rows_len3[:], rows_len3[:], rows_len3[:] ], 5 ) ################ def M3x3_list_reversed_1stEls( _e1=[2, 3, 1], _e2=[4, 3, 0], _e3=[5, 2, 8] ): """Ką atspausdins? (atskirkite tarpais)""" M = [ _e1, _e2, _e3, ] for k in range(3): print( M[2-k][0] ) __randchoice_questions(M3x3_list_reversed_1stEls, [ rows_len3, rows_len3, rows_len3 ], 5 ) ################################# ################################# # # NonSquare Matrix # ################################# ################################# ################ def M_midle_elements( _e1=[2, 3, 1, 8], _e2=[4, 1, 5, 3, 0], _e3=[5, 2, 8] ): """Ką atspausdins? (atskirkite tarpais)""" M = [ _e1, _e2, _e3, ] n = len(M) for k in range(n): a = len(M[k]) // 2 # // suapvalina dalybos rez. į mažesnę pusę print( M[k][a] ) __randchoice_questions(M_midle_elements, [ rows_len3, rows_len5, rows_len4 ], 5 ) ################ def M_last_elements( _e1=[2, 3, 1], _e2=[4, 3], _e3=[5, 2, 8, 9] ): """Ką atspausdins? (atskirkite tarpais)""" M = [ _e1, _e2, _e3, ] for row in M: a = len(row)-1 print( row[a] ) __randchoice_questions(M_last_elements, [ rows_len3, rows_len5, rows_len4 ], 5 ) ################ def M_lengths_M_and_Rows( _e1=[2, 3, 1], _e2=[4, 3, 8, 0], _e3=[5, 2, 8] ): """Ką atspausdins? (atskirkite tarpais)""" M = [ _e1, _e2, _e3, ] print(len(M)) for row in M: print( len(row) ) __randchoice_questions(M_lengths_M_and_Rows, [ rows_len4, rows_len3, rows_len5 ], 5 ) ################ def M_lengths_M_and_Rows( _e1=[2, 3, 1], _e2=[4, 3, 0], _e3=[5, 2, 8] ): """Ką atspausdins? (atskirkite tarpais)""" M = [ _e1, _e2, _e3, ] print(len(M)) for row in M: print( len(row) ) __randchoice_questions(M_lengths_M_and_Rows, [ rows_len4, rows_len3, rows_len5 ], 5 ) ################ def M_SumColsAndRows( _a=1, _b=2, _e1=[2, 3, 1], _e2=[4, 3, 8, 0], _e3=[5, 2, 8] ): """Ką atspausdins? (atskirkite tarpais)""" def sum_col(X, nr): s = 0 for row in X: s += row[nr] return s def row_col(X, nr): return sum(X[nr]) M = [ _e1, _e2, _e3, ] print( sum_col(M, _a), row_col(M, _b) ) __randchoice_questions(M_SumColsAndRows, [range(3), range(3), rows_len4, rows_len3, rows_len5 ], 5 ) ################ def M_AppendRow_QUITE_HARD( _e1=[2, 3, 1], _e2=[4, 3, 8, 0] ): """Ką atspausdins? (atskirkite tarpais)""" M = [ _e1, _e2, ] p = len(M[0]) sar = [] for k in range(p): sar.append( M[0][k] + M[1][k] ) M.append(sar) n = len(M) print(M[n-1][n]) __randchoice_questions(M_AppendRow_QUITE_HARD, [ rows_len4, rows_len4], 5 ) def M_maxEl_QUITE_HARD(_a=3, _e1=[2, 3, 1], _e2=[4, 3, 8, 0], _e3=range(5) ): """Ką atspausdins? (atskirkite tarpais)""" M = [ _e1, _e2, _e3 ] x = _a n = len(M) for k in range(n): for j in range( len(M[k]) ): if x < M[k][j]: x = M[k][j] print(k, j, x, '/') __randchoice_questions(M_maxEl_QUITE_HARD, [ range(5), rows_len4, rows_len3, rows_len4], 5 )
[ [ 1, 0, 0.0057, 0.0029, 0, 0.66, 0, 715, 0, 2, 0, 0, 715, 0, 0 ], [ 2, 0, 0.0229, 0.0143, 0, 0.66, 0.0233, 325, 0, 3, 0, 0, 0, 0, 4 ], [ 8, 1, 0.0201, 0.0029, 1, 0....
[ "from random import randint, choice", "def __rand_questions(fun, args_intervals, how_many):\n __print_category(fun.__name__+'_RANDOM')\n for i in range(how_many):\n args = [randint(*interval) for interval in args_intervals]\n fun( *args )", " __print_category(fun.__name__+'_RANDOM')", ...
# Also of interest: # http://docs.moodle.org/25/en/Programmed_responses_question_type # http://docs.moodle.org/25/en/question/type/correctwriting -- sakinio struktūros klausimai # http://docs.moodle.org/25/en/Multinumerical_question_type # http://docs.moodle.org/dev/Opaque #~ from random import randint #~ def Arithmetics_2operations(_sign1='+', _sign2='*', _a=13, _b=5, _c=7): #~ __tpl =""" #~ rez = _a _sign1 _b _sign2 _c #~ print(rez) #~ """ try: from tpl_helpers import __rand_questions, __print_category except ImportError: from .tpl_helpers import __rand_questions, __print_category ############ Arithmetics ######### def Arithmetics_simple1(_a, _b, _c): """Kam bus lygus x?""" x = _a * _b - _c # skaičiuojam HIDEEXACT(*) print (x) def Arithmetics_simple2(_a, _b, _c): """Kam bus lygus x ir y? (atskirkite tarpais)""" x = _a - _c y = _a + x * _b # HIDEEXACT(* _b) print (x, y) def Arithmetics_simple3(_a, _b, _c): """Kam bus lygus x?""" a = _a b = _b x = a - _c * (b - a) print (x) __rand_questions(Arithmetics_simple1, [(1, 9), (3, 9), (1, 9)], 5 ) __rand_questions(Arithmetics_simple2, [(1, 9), (3, 9), (1, 9)], 5 ) __rand_questions(Arithmetics_simple3, [(1, 9), (3, 9), (1, 9)], 5 ) ############ Variables ######### def Var_Arithmetic_PlusMult(_a=2, _b=5, _c=3): # {=%(track['x'])s} """Ką atspausdins?""" x = _a x = x + _b # HIDE(+) print(x) x = _c * x # HIDE(*) print(x) def Variables_simple1(_a, _b): """Kiek pinigų turėsime pabaigoje?""" pinigai = _a # pradinė piginų suma kebabas = _b pinigai = pinigai - kebabas # kintamojo pakeitimas print (pinigai) def Variables_simple2(_a, _b): """Kiek nupirks porcijų ir kiek liks pinigų?""" pinigai = _a # pradinė piginų suma kebabas = _b # kebabo kaina porcijos = pinigai // kebabas # suapvalinanti dalyba pinigai = pinigai - porcijos*kebabas # likutis print (porcijos, pinigai) def Variables_and_IF1(_a, _b, _c): """Kiek nupirks porcijų ir kiek liks pinigų?""" pinigai = _a # pradinė piginų suma kebabas = _b # kebabo kaina draugai = _c porcijos = pinigai // kebabas # suapvalinanti dalyba "//" if porcijos > draugai+1: porcijos = draugai+1 # užteks kiekvienam po vieną porciją islaidos = porcijos * kebabas pinigai = pinigai - islaidos print (porcijos, pinigai) __rand_questions( Var_Arithmetic_PlusMult, [(-9, 9), (2, 9), (3, 9)], 5 ) __rand_questions( Variables_simple1, [(10, 20), (2, 9)], 5 ) __rand_questions( Variables_simple2, [(10, 30), (3, 7)], 5) __rand_questions( Variables_and_IF1, [(10, 50), (3, 7), (0, 5)], 7 ) ################ IF ELIF ############# def IfElifElse(_a, _b=12, _c=8): # {=%(out)s} """What will be printed?""" a = _a if a > _b: print("big") elif a > _c: print("average") else: print("small") # the variations of question __print_category('IfElifElse_FIXED') IfElifElse(10, 18) IfElifElse(10, 18, 10) IfElifElse(12, 12, 10) IfElifElse(5, 12, 10) IfElifElse(15, 12, 10) __rand_questions( IfElifElse, [(10, 99), (10, 99), (10, 99)], 5) #~ for i in range(5): #~ IfElifElse( randint(10, 99), randint(10, 99), randint(10, 99) )
[ [ 7, 0, 0.1555, 0.0336, 0, 0.66, 0, 0, 0, 1, 0, 0, 0, 0, 0 ], [ 1, 1, 0.1513, 0.0084, 1, 0.5, 0, 125, 0, 2, 0, 0, 125, 0, 0 ], [ 1, 1, 0.1681, 0.0084, 1, 0.5, 0...
[ "try:\n from tpl_helpers import __rand_questions, __print_category\nexcept ImportError:\n from .tpl_helpers import __rand_questions, __print_category", " from tpl_helpers import __rand_questions, __print_category", " from .tpl_helpers import __rand_questions, __print_category", "def Arithmetics_si...
from random import randint import os import inspect def __print_category(cat_name, sub_path='Testas-X', _type="GIFT"): if sub_path: cat_name = sub_path+'/'+cat_name if _type=="GIFT": print("\n$CATEGORY: $system$/%s\n" % cat_name ) if _type=="CLOZE": print(""" <question type="category"> <category> <text>$system$/%s</text> </category> </question> """ % ( cat_name) ) def __rand_questions(fun, args_intervals, how_many, sub_path='', _type="GIFT"): __print_category(fun.__name__+'_RANDOM', sub_path=sub_path, _type=_type) for i in range(how_many): args = [randint(*interval) for interval in args_intervals] #~ fun( *args ) __question(fun, args=args) ########### via decorators ############ def __parent_dir_2path(): import os,sys,inspect currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) parentdir = os.path.dirname(currentdir) sys.path.insert(0,parentdir) __parent_dir_2path() #~ generate_via_decorators = __import__("generate_via_decorators") ###################### NG (not finished) - MORE STRUCTURED question collecting approach ########## def __category(cat_name, stack=None): if stack: stack.append( dict(cat_name=cat_name, questions=[] ) ) else: __print_category(cat_name) # legacy pass def __question(fun, args, kwargs=None, stack=None): if kwargs is None: kwargs = {} if stack: if stack == []: __category('Unnamed', stack) #~ start_output_caching() #~ fun( *args, **kwargs ) #~ output = finish_output_caching() stack[-1]['questions'].append( dict( src = inspect.getsource(fun), output = output , #~ question = , #~ answer = )) else: #~ print("***") #~ print(inspect.getsource(fun)) fun( *args, **kwargs ) # legacy
[ [ 1, 0, 0.0149, 0.0149, 0, 0.66, 0, 715, 0, 1, 0, 0, 715, 0, 0 ], [ 1, 0, 0.0299, 0.0149, 0, 0.66, 0.125, 688, 0, 1, 0, 0, 688, 0, 0 ], [ 1, 0, 0.0448, 0.0149, 0, 0...
[ "from random import randint", "import os", "import inspect", "def __print_category(cat_name, sub_path='Testas-X', _type=\"GIFT\"):\n\n if sub_path: cat_name = sub_path+'/'+cat_name\n \n if _type==\"GIFT\":\n print(\"\\n$CATEGORY: $system$/%s\\n\" % cat_name )\n \n if _type==\"CLOZE\...
# http://docs.python.org/3.2/tutorial/errors.html # http://docs.python.org/3.2/library/exceptions.html#bltin-exceptions """ invalid syntax name '….' is not defined unindent does not match any outer indentation level expected an indented block can't assign to operator can't assign to literal """ """ a = 1 while b < 20 Print(b) tmp = b if a > b: print("a daugiau elif b > a : prnt("b daugiau") else: print(lygu) b = b + a a + b = tmp """ #~ def SyntaxNoColumn(): #~ a = 0 #~ while a < 5 #~ print (a) def NameUndefined1(): # NameError: global name '....' is not defined while a < 5: print (a) #~ NameUndefined1() #~ def NameWhileMisspelled1(): # SyntaxError: invalid syntax #~ b = 1 #~ wihle b < 5: #~ print (b) #~ #~ NameWhileMisspelled1() def NamePrintMisspelled1(): # NameError: global name '....' is not defined b = 1 while b < 5: Print (b) #~ NamePrintMisspelled1() def NamePrintMisspelled2(): # NameError: global name '....' is not defined for a in range(5): prnt(a) #~ NamePrintMisspelled2() def input_int(txt): pass #~ def Unindent(): # IndentationError: unindent does not match any outer indentation level #~ a = input_int("Jūsų vidurkis:") #~ if a > 8: #~ print( "neblogai" ) #~ print("bet reikia stengtis") #~ def IndentedExpected(): # IndentationError: expected an indented block #~ a = input_int("Jūsų vidurkis:") #~ if a > 8: #~ print( "neblogai" ) #~ if a > 9.5: #~ print("ir netgi puikiai!") #~ else: #~ print("šiaip sau..") #~ IndentedExpected() #~ #~ def AssignmentToOperator(): # SyntaxError: can't assign to operator #~ a = 5 #~ a + 3 = a #~ AssignmentToOperator() #~ def AssignmentToLiteral(): # SyntaxError: can't assign to literal #~ 3 = b #~ b = b+1 #~ #~ AssignmentToLiteral() #~ def SyntaxPrintMissingSeparator(): # SyntaxError: invalid syntax #~ for a in range(5): #~ print("a yra" a) #~ PrintMissingSeparator() def ArgumentsMissing1(): # TypeError: count() takes exactly 1 argument (0 given) def count( n ): while n > 0: print(n) n = n-1 n = 2 count() #~ ArgumentsMissing1() def ArgumentsTooMuch(): # TypeError: pasisveikink() takes no arguments (1 given) def pasisveikink(): print("Labas") pasisveikink("Pasauli") #~ ArgumentsTooMuch() def ZeroDivisionError(): # ZeroDivisionError: division by zero for a in range(5): print( 10 / a ) #~ ZeroDivisionError() def TypeIntPlusStr(): # TypeError: unsupported operand type(s) for -: 'int' and 'str' info = "Aš turiu 20 Lt".split() # ['Aš', 'turiu', '20', 'Lt'] reikia = 50 truskta = reikia - info[2] #~ TypeIntPlusStr() def Type_CantConvertStrToInt(): # ValueError: invalid literal for int() with base 10: '....' info = "Aš turiu 20 Lt".split() # ['Aš', 'turiu', '20', 'Lt'] turiu = int( info[3] ) reikia = 50 truskta = reikia - turiu #~ Type_CantConvertStrToInt() def IO(): # IOError: [Errno 2] No such file or directory: '.........' open("failas.txt", 'r')
[ [ 8, 0, 0.0567, 0.0638, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 8, 0, 0.1454, 0.0993, 0, 0.66, 0.0909, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 2, 0, 0.2553, 0.0213, 0, 0.66, ...
[ "\"\"\"\ninvalid syntax \nname '….' is not defined\nunindent does not match any \nouter indentation level \nexpected an indented block\ncan't assign to operator\ncan't assign to literal", "\"\"\"\na = 1\nwhile b < 20\n Print(b)\n tmp = b\n if a > b:\n print(\"a daugiau\n eli...
try: from tpl_helpers import __rand_questions, __print_category except ImportError: from .tpl_helpers import __rand_questions, __print_category def test_gap_with_alternatives(_a=7): x = _a if x > 10: # alternative could be in C: "or" vs "||" HIDE(x >)~(=x>\=) print("big") else: print("small") def test_gap_with_baseword(_a=7): x = _a if x > 10: # HIDE( if ) print("big") else: # HIDE( else : )~(if 1#bet yra gudresnių variantų) print("small") def test_gap_with_partof_baseword(_a=7): x = _a if x > 10: print("big part") else: # HIDE(lse) print("small part") def test_gaps(_a=7): x = _a print(x) x = 11 + x # HIDE(x) HIDE(11 +)~(=2*#also possible) print(x) # spausdina antrąkart # HIDE(print) def test_gap(_a=7): x = _a print(x) x = x + 11 # HIDE(+) print(x) def test_gap_with_spec_chars(_a=7): x = _a print("big ~\# part") # HIDE(() HIDE(part") def test_gap_with_spec_chars_HIDEEXACT_tilde_and_backslash(): print("~\ # stuff") # HIDEEXACT(\~\ #) print("~\# stuff") # HIDEEXACT(\~\#) print("~\# stuff") # HIDEEXACT(\#) print("~\# stuff") # HIDEEXACT(#) print("~\# stuff") # HIDEEXACT(\~) print("~\# stuff") # HIDEEXACT(\) def test_gap_with_spec_chars_dict(_a=7): x = _a d={x:4} # HIDE(d=) print(d) def test_gap_with_spec_chars_dict_hide_dict(_a=7): x = _a d={x:4} # HIDE({) print(d) def test_gap_with_spec_chars_hide_comment_sign(_a=7): x = _a print(x) # bla bla HIDE( (x) # ) ~%20%(x)# gaunate tik 20%, nes lieka sintaksės klaida... def test_gap_HIDEREGEXP(_a=7): x = _a + 5 # HIDEREGEXP(\d *\+) print(x) # **************************************** __print_category('Bandymai', sub_path="FillGaps", _type="CLOZE") test_gap() test_gaps() test_gap_with_alternatives() test_gap_with_baseword() test_gap_with_partof_baseword() test_gap_with_spec_chars() test_gap_with_spec_chars_dict() test_gap_with_spec_chars_dict_hide_dict() test_gap_with_spec_chars_HIDEEXACT_tilde_and_backslash() test_gap_with_spec_chars_hide_comment_sign() test_gap_HIDEREGEXP() #~ __rand_questions( test_gaps, [(1, 20)], 5 , sub_path='FillGaps/Bandymai', _type="CLOZE")
[ [ 7, 0, 0.0287, 0.046, 0, 0.66, 0, 0, 0, 1, 0, 0, 0, 0, 0 ], [ 1, 1, 0.023, 0.0115, 1, 0.85, 0, 125, 0, 2, 0, 0, 125, 0, 0 ], [ 1, 1, 0.046, 0.0115, 1, 0.85, 0,...
[ "try:\n from tpl_helpers import __rand_questions, __print_category\nexcept ImportError:\n from .tpl_helpers import __rand_questions, __print_category", " from tpl_helpers import __rand_questions, __print_category", " from .tpl_helpers import __rand_questions, __print_category", "def test_gap_with_...
import inspect import pygments import re #~ from Questions_tpl.variables_and_conditions import * from pygments.lexers import PythonLexer, CppLexer pylexer = lexer = PythonLexer(ensurenl=False) cpplexer = CppLexer(ensurenl=False) def adapt_code_spacing(code, unneeded='', needed_once=' ', ignore_space_after_escape_chars=True, lang='py' ): # delete unneeded spaces, without changing the meaning """ a = 5 while a> 2: if a != 3: print(a,"Hello World" ) a -= 1 """ #~ print( list( lexer.get_tokens( code ) ) ) #~ print ( "**********************"); print(); rez = '' prevtype=None prevval=None if lang=='cpp': lexer = cpplexer else: lexer = pylexer for t in lexer.get_tokens( code ) : #~ print(t) ttype, tval = t if prevtype: if str(ttype)=='Token.Text' and tval.strip(' \t')=='': # is space if str(prevtype) == 'Token.Keyword': tval = needed_once elif not prevval.endswith('\n'): tval = unneeded elif not( str(prevtype)=='Token.Text' and prevval.strip(' \t')=='') : # was not space #~ if not re.search(ignore_whenprev, prevval): if not prevval.endswith( '\\' ) or not ignore_space_after_escape_chars: rez += unneeded prevtype, prevval = t; rez += tval #~ print(tval, end='') return rez.rstrip('\n') def regexpize_code_spacing(code, lang='py'): return adapt_code_spacing(code, unneeded=' *', needed_once=' +', lang=lang) def minimize_code_spacing(code, lang='py'): return adapt_code_spacing(code, lang=lang) def split_off_comment(line, lang='py'): rez_line = '' if lang=='cpp': lexer = cpplexer else: lexer = pylexer #~ print("##", line) prev_tval = '' for ttype, tval in lexer.get_tokens( line ): #~ print('##', ttype, tval) if lang=='cpp' and str(ttype) == 'Token.Operator' and tval=='/' and prev_tval=='/': return rez_line[:-1], line[len(rez_line)-1:] elif str(ttype) == 'Token.Comment': return rez_line, tval else: rez_line += tval prev_tval = tval return line, None def prepair_gaps(code, SHOWERRORS=True, lang='py'): gaps = [] lines = [] for lnr, line in enumerate(code.splitlines() ): line, comment = split_off_comment(line, lang=lang) if comment and ('HIDE' in comment): comment_beginning, *search_patterns = comment.split('HIDE') cb = comment_beginning.rstrip(' #\t') if lang=='cpp' and cb.endswith('//'): cb=cb.rstrip('/'); line = line + cb for pattern in search_patterns: pattern, *alternatives = re.split (r"(?<!\\)\~", pattern) # moodle GIFT style alternatives are separated with ~ # alternatives are good for feedback for "near miss" answers # if you use ~ literraly, must escape it with \~ # for GIFT, one should escape \}#~/"' alternatives = '~'.join(alternatives) # join back alternatives to string :) EXACT = pattern.startswith('EXACT') REGEXP = pattern.startswith('REGEXP') if EXACT: pattern = pattern[len('EXACT'):] #trim 'EXACT' if REGEXP: pattern = pattern[len('REGEXP'):] #trim 'REGEXP' pattern = pattern.strip() if pattern.startswith('(') and pattern.endswith(')'): pattern = pattern[1:-1] pattern = pattern.strip() # strip spaces -- as they are ignored by Moodle short answer anyway pattern = pattern.replace('\\~', '~') # unescape \~ answer = None if EXACT: if pattern in line: answer = pattern elif REGEXP: regexp_match = re.search(pattern, line) if regexp_match: answer = regexp_match.group(0) else: for s in '\\.+*?^$!(){,}<>=:|': # escape regexp spec. chars pattern = pattern.replace(s, '\\'+s) regexp = regexpize_code_spacing(pattern, lang=lang) #~ print('pattern regexp:', regexp) regexp_match = re.search(regexp, line) if regexp_match: answer = regexp_match.group(0) if answer: line = line.replace( answer, '..%s....' % (len(gaps)), 1) #~ print('ANSW', lnr, (answer,)) if not EXACT: answer = minimize_code_spacing(answer, lang=lang) if alternatives: gaps.append( (lnr, [answer, alternatives] ) ) else: gaps.append( (lnr, answer) ) elif SHOWERRORS: print("<!-- ANSWER for pattern '%s' NOT FOUND on line nr. %s: %s -->" % (pattern, lnr, line)) #~ print(line) lines.append(line) return ('\n'.join(lines), gaps) if __name__ == '__main__': #~ code = inspect.getsource(test_gap_with_alternatives) #~ code = inspect.getsource(test_gap_with_baseword) from Questions_tpl.fill_missing_tests import * code = inspect.getsource(test_gap_with_spec_chars_HIDEEXACT_tilde_and_backslash) #~ code = inspect.getsource(test_gap_HIDEREGEXP) for x in prepair_gaps(code): print(x)
[ [ 1, 0, 0.0197, 0.0066, 0, 0.66, 0, 878, 0, 1, 0, 0, 878, 0, 0 ], [ 1, 0, 0.0263, 0.0066, 0, 0.66, 0.0909, 638, 0, 1, 0, 0, 638, 0, 0 ], [ 1, 0, 0.0329, 0.0066, 0, ...
[ "import inspect", "import pygments", "import re", "from pygments.lexers import PythonLexer, CppLexer", "pylexer = lexer = PythonLexer(ensurenl=False)", "cpplexer = CppLexer(ensurenl=False)", "def adapt_code_spacing(code, unneeded='', needed_once=' ', ignore_space_after_escape_chars=True, lang='py' ): #...
# -*- coding: utf-8 -*- """ codegen ~~~~~~~ Extension to ast that allow ast -> python code generation. :copyright: Copyright 2008 by Armin Ronacher. :license: BSD. """ from ast import * BOOLOP_SYMBOLS = { And: 'and', Or: 'or' } BINOP_SYMBOLS = { Add: '+', Sub: '-', Mult: '*', Div: '/', FloorDiv: '//', Mod: '%', LShift: '<<', RShift: '>>', BitOr: '|', BitAnd: '&', BitXor: '^' } CMPOP_SYMBOLS = { Eq: '==', Gt: '>', GtE: '>=', In: 'in', Is: 'is', IsNot: 'is not', Lt: '<', LtE: '<=', NotEq: '!=', NotIn: 'not in' } UNARYOP_SYMBOLS = { Invert: '~', Not: 'not', UAdd: '+', USub: '-' } ALL_SYMBOLS = {} ALL_SYMBOLS.update(BOOLOP_SYMBOLS) ALL_SYMBOLS.update(BINOP_SYMBOLS) ALL_SYMBOLS.update(CMPOP_SYMBOLS) ALL_SYMBOLS.update(UNARYOP_SYMBOLS) def to_source(node, indent_with=' ' * 4, add_line_information=False): """This function can convert a node tree back into python sourcecode. This is useful for debugging purposes, especially if you're dealing with custom asts not generated by python itself. It could be that the sourcecode is evaluable when the AST itself is not compilable / evaluable. The reason for this is that the AST contains some more data than regular sourcecode does, which is dropped during conversion. Each level of indentation is replaced with `indent_with`. Per default this parameter is equal to four spaces as suggested by PEP 8, but it might be adjusted to match the application's styleguide. If `add_line_information` is set to `True` comments for the line numbers of the nodes are added to the output. This can be used to spot wrong line number information of statement nodes. """ generator = SourceGenerator(indent_with, add_line_information) generator.visit(node) print (generator.result) return ''.join(generator.result) class SourceGenerator(NodeVisitor): """This visitor is able to transform a well formed syntax tree into python sourcecode. For more details have a look at the docstring of the `node_to_source` function. """ def __init__(self, indent_with=' '*4, add_line_information=False): self.result = [] self.indent_with = indent_with self.add_line_information = add_line_information self.indentation = 0 self.new_lines = 0 def write(self, x): if self.new_lines: if self.result: self.result.append('\n' * self.new_lines) self.result.append(self.indent_with * self.indentation) self.new_lines = 0 self.result.append(x) def newline(self, node=None, extra=0): self.new_lines = max(self.new_lines, 1 + extra) if node is not None and self.add_line_information: self.write('# line: %s' % node.lineno) self.new_lines = 1 def body(self, statements): self.new_line = True self.indentation += 1 for stmt in statements: self.visit(stmt) self.indentation -= 1 def body_or_else(self, node): self.body(node.body) if node.orelse: self.newline() self.write('else:') self.body(node.orelse) def signature(self, node): want_comma = [] def write_comma(): if want_comma: self.write(', ') else: want_comma.append(True) padding = [None] * (len(node.args) - len(node.defaults)) for arg, default in zip(node.args, padding + node.defaults): write_comma() self.visit(arg) if default is not None: self.write('=') self.visit(default) if node.vararg is not None: write_comma() self.write('*' + node.vararg) if node.kwarg is not None: write_comma() self.write('**' + node.kwarg) def decorators(self, node): for decorator in node.decorator_list: self.newline(decorator) self.write('@') self.visit(decorator) # Statements def visit_Assign(self, node): self.newline(node) for idx, target in enumerate(node.targets): if idx: self.write(', ') self.visit(target) self.write(' = ') self.visit(node.value) def visit_AugAssign(self, node): self.newline(node) self.visit(node.target) self.write(BINOP_SYMBOLS[type(node.op)] + '=') self.visit(node.value) def visit_ImportFrom(self, node): self.newline(node) self.write('from %s%s import ' % ('.' * node.level, node.module)) for idx, item in enumerate(node.names): if idx: self.write(', ') self.write(item) def visit_Import(self, node): self.newline(node) for item in node.names: self.write('import ') self.visit(item) def visit_Expr(self, node): self.newline(node) self.generic_visit(node) def visit_FunctionDef(self, node): self.newline(extra=1) self.decorators(node) self.newline(node) self.write('def %s(' % node.name) self.signature(node.args) self.write('):') self.body(node.body) def visit_ClassDef(self, node): have_args = [] def paren_or_comma(): if have_args: self.write(', ') else: have_args.append(True) self.write('(') self.newline(extra=2) self.decorators(node) self.newline(node) self.write('class %s' % node.name) for base in node.bases: paren_or_comma() self.visit(base) # XXX: the if here is used to keep this module compatible # with python 2.6. if hasattr(node, 'keywords'): for keyword in node.keywords: paren_or_comma() self.write(keyword.arg + '=') self.visit(keyword.value) if node.starargs is not None: paren_or_comma() self.write('*') self.visit(node.starargs) if node.kwargs is not None: paren_or_comma() self.write('**') self.visit(node.kwargs) self.write(have_args and '):' or ':') self.body(node.body) def visit_If(self, node): self.newline(node) self.write('if ') self.visit(node.test) self.write(':') self.body(node.body) while True: else_ = node.orelse if len(else_) == 1 and isinstance(else_[0], If): node = else_[0] self.newline() self.write('elif ') self.visit(node.test) self.write(':') self.body(node.body) else: if else_: self.newline() self.write('else:') self.body(else_) break def visit_For(self, node): self.newline(node) self.write('for ') self.visit(node.target) self.write(' in ') self.visit(node.iter) self.write(':') self.body_or_else(node) def visit_While(self, node): self.newline(node) self.write('while ') self.visit(node.test) self.write(':') self.body_or_else(node) def visit_With(self, node): self.newline(node) self.write('with ') self.visit(node.context_expr) if node.optional_vars is not None: self.write(' as ') self.visit(node.optional_vars) self.write(':') self.body(node.body) def visit_Pass(self, node): self.newline(node) self.write('pass') def visit_Print(self, node): # XXX: python 2.6 only self.newline(node) self.write('print ') want_comma = False if node.dest is not None: self.write(' >> ') self.visit(node.dest) want_comma = True for value in node.values: if want_comma: self.write(', ') self.visit(value) want_comma = True if not node.nl: self.write(',') def visit_Delete(self, node): self.newline(node) self.write('del ') for idx, target in enumerate(node): if idx: self.write(', ') self.visit(target) def visit_TryExcept(self, node): self.newline(node) self.write('try:') self.body(node.body) for handler in node.handlers: self.visit(handler) def visit_TryFinally(self, node): self.newline(node) self.write('try:') self.body(node.body) self.newline(node) self.write('finally:') self.body(node.finalbody) def visit_Global(self, node): self.newline(node) self.write('global ' + ', '.join(node.names)) def visit_Nonlocal(self, node): self.newline(node) self.write('nonlocal ' + ', '.join(node.names)) def visit_Return(self, node): self.newline(node) self.write('return ') self.visit(node.value) def visit_Break(self, node): self.newline(node) self.write('break') def visit_Continue(self, node): self.newline(node) self.write('continue') def visit_Raise(self, node): # XXX: Python 2.6 / 3.0 compatibility self.newline(node) self.write('raise') if hasattr(node, 'exc') and node.exc is not None: self.write(' ') self.visit(node.exc) if node.cause is not None: self.write(' from ') self.visit(node.cause) elif hasattr(node, 'type') and node.type is not None: self.visit(node.type) if node.inst is not None: self.write(', ') self.visit(node.inst) if node.tback is not None: self.write(', ') self.visit(node.tback) # Expressions def visit_Attribute(self, node): self.visit(node.value) self.write('.' + node.attr) def visit_Call(self, node): want_comma = [] def write_comma(): if want_comma: self.write(', ') else: want_comma.append(True) self.visit(node.func) self.write('(') for arg in node.args: write_comma() self.visit(arg) for keyword in node.keywords: write_comma() self.write(keyword.arg + '=') self.visit(keyword.value) if node.starargs is not None: write_comma() self.write('*') self.visit(node.starargs) if node.kwargs is not None: write_comma() self.write('**') self.visit(node.kwargs) self.write(')') def visit_Name(self, node): self.write(node.id) def visit_Str(self, node): self.write(repr(node.s)) def visit_Bytes(self, node): self.write(repr(node.s)) def visit_Num(self, node): self.write(repr(node.n)) def visit_Tuple(self, node): self.write('(') idx = -1 for idx, item in enumerate(node.elts): if idx: self.write(', ') self.visit(item) self.write(idx and ')' or ',)') def sequence_visit(left, right): def visit(self, node): self.write(left) for idx, item in enumerate(node.elts): if idx: self.write(', ') self.visit(item) self.write(right) return visit visit_List = sequence_visit('[', ']') visit_Set = sequence_visit('{', '}') del sequence_visit def visit_Dict(self, node): self.write('{') for idx, (key, value) in enumerate(zip(node.keys, node.values)): if idx: self.write(', ') self.visit(key) self.write(': ') self.visit(value) self.write('}') def visit_BinOp(self, node): self.visit(node.left) self.write(' %s ' % BINOP_SYMBOLS[type(node.op)]) self.visit(node.right) def visit_BoolOp(self, node): self.write('(') for idx, value in enumerate(node.values): if idx: self.write(' %s ' % BOOLOP_SYMBOLS[type(node.op)]) self.visit(value) self.write(')') def visit_Compare(self, node): self.write('(') self.visit(node.left) for op, right in zip(node.ops, node.comparators): self.write(' %s ' % CMPOP_SYMBOLS[type(op)]) self.visit(right) self.write(')') def visit_UnaryOp(self, node): self.write('(') op = UNARYOP_SYMBOLS[type(node.op)] self.write(op) if op == 'not': self.write(' ') self.visit(node.operand) self.write(')') def visit_Subscript(self, node): self.visit(node.value) self.write('[') self.visit(node.slice) self.write(']') def visit_Slice(self, node): if node.lower is not None: self.visit(node.lower) self.write(':') if node.upper is not None: self.visit(node.upper) if node.step is not None: self.write(':') if not (isinstance(node.step, Name) and node.step.id == 'None'): self.visit(node.step) def visit_ExtSlice(self, node): for idx, item in node.dims: if idx: self.write(', ') self.visit(item) def visit_Yield(self, node): self.write('yield ') self.visit(node.value) def visit_Lambda(self, node): self.write('lambda ') self.signature(node.args) self.write(': ') self.visit(node.body) def visit_Ellipsis(self, node): self.write('Ellipsis') def generator_visit(left, right): def visit(self, node): self.write(left) self.visit(node.elt) for comprehension in node.generators: self.visit(comprehension) self.write(right) return visit visit_ListComp = generator_visit('[', ']') visit_GeneratorExp = generator_visit('(', ')') visit_SetComp = generator_visit('{', '}') del generator_visit def visit_DictComp(self, node): self.write('{') self.visit(node.key) self.write(': ') self.visit(node.value) for comprehension in node.generators: self.visit(comprehension) self.write('}') def visit_IfExp(self, node): self.visit(node.body) self.write(' if ') self.visit(node.test) self.write(' else ') self.visit(node.orelse) def visit_Starred(self, node): self.write('*') self.visit(node.value) def visit_Repr(self, node): # XXX: python 2.6 only self.write('`') self.visit(node.value) self.write('`') # Helper Nodes def visit_alias(self, node): self.write(node.name) if node.asname is not None: self.write(' as ' + node.asname) def visit_comprehension(self, node): self.write(' for ') self.visit(node.target) self.write(' in ') self.visit(node.iter) if node.ifs: for if_ in node.ifs: self.write(' if ') self.visit(if_) def visit_excepthandler(self, node): self.newline(node) self.write('except') if node.type is not None: self.write(' ') self.visit(node.type) if node.name is not None: self.write(' as ') self.visit(node.name) self.write(':') self.body(node.body)
[ [ 8, 0, 0.0105, 0.0157, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 1, 0, 0.0192, 0.0017, 0, 0.66, 0.0833, 809, 0, 1, 0, 0, 809, 0, 0 ], [ 14, 0, 0.027, 0.007, 0, 0.66,...
[ "\"\"\"\n codegen\n ~~~~~~~\n\n Extension to ast that allow ast -> python code generation.\n\n :copyright: Copyright 2008 by Armin Ronacher.\n :license: BSD.", "from ast import *", "BOOLOP_SYMBOLS = {\n And: 'and',\n Or: 'or'\n}", "BINOP_SYMBOLS = {\n Add: '+',\n ...
s = 5 for x in [1, 3, 2]: print('1st', x) if x > 2: for z in range(2): print('2nd') print('bla') for i in range(x): a = i print('3rd', i) print('back to 1st') print('end')
[ [ 14, 0, 0.0909, 0.0909, 0, 0.66, 0, 553, 1, 0, 0, 0, 0, 1, 0 ], [ 6, 0, 0.5455, 0.8182, 0, 0.66, 0.5, 190, 0, 0, 0, 0, 0, 0, 7 ], [ 8, 1, 0.2727, 0.0909, 1, 0.42, ...
[ "s = 5", "for x in [1, 3, 2]:\n print('1st', x)\n if x > 2:\n for z in range(2): print('2nd')\n print('bla')\n for i in range(x):\n a = i\n print('3rd', i)", " print('1st', x)", " if x > 2:\n for z in range(2): print('2nd')\n print('bla')\n ...
import re re_docs = re.compile(r'"""(.*?)"""', re.DOTALL) import py2cpp from pygments.lexers import PythonLexer lexer = PythonLexer(ensurenl=False) def delete_comments(src, containing=''): lines = src.split('\n') for nr, line in enumerate(lines): for t in lexer.get_tokens( line ): #~ print(t) ttype, tval = t if str(ttype)=='Token.Comment': # single? TODO if containing and containing in tval: line, comment, right_empty_bla = line.rpartition(tval) comment, fragment, ritht_blah = comment.partition(containing) if comment.rstrip('\t #')!='': line += comment if containing=='': # just chop whole comment line, comment, right_empty_bla = line.rpartition(tval) lines[nr] = line return '\n'.join(lines) def replace_placeholders_to_values(src, f_args=[], f_locals={}): """ substitute param names with their values """ for param in sorted(f_args): # sorted puts params with more prepended underscores first -- important for HIDE pattern if param.startswith('_'): re_param = re.compile(r'\b%s\b'%param) #~ if param.startswith('__'): # where extra quotes are not needed #~ replacement = str(f_locals[param]) #~ else: #~ replacement = repr(f_locals[param]) #~ src = re.sub(re_param, replacement, src ) src = re.sub(re_param, str(f_locals[param]), src ) return src import fill_missing_code def src_to_CLOZE(title, src, f_args=[], f_locals={}, CONVERT2CPP=False, question_text='', lang_code2img='', title_without_hints='', pygmentize=False): src = replace_placeholders_to_values(src, f_args, f_locals) #~ print(src) if CONVERT2CPP: src = py2cpp.convert(src, GIFT=False) #~ print(src) lang = 'cpp' if CONVERT2CPP else 'py' question, answers = fill_missing_code.prepair_gaps(src, SHOWERRORS=True, lang=lang ) # questin is with gaps of format: ..<n>.... #~ print ("Q:", question) if len(answers)==0: # if no answers prepaired, no question will be given return '' if pygmentize: question = code2pygmetshtml(question, lang, linenos=False, inlineCSS=True) for nr, (line_nr, a) in enumerate(answers): # about SHORTANSWER https://docs.moodle.org/26/en/Embedded_Answers_%28Cloze%29_question_type#Detailed_syntax_explanations alternatives = '' if isinstance(a, (list, tuple)): a, alternatives = a #~ alternatives = [escape_answer(alt) for alt in alternatives] -- should be escaped manulally if alternatives: alternatives += "~" # joining symbol alternatives += ("*#atsakymui reik %s simboli" % len(a)) + ('o' if len(a)==1 else 'ų') a = escape_CLOZE_answer_chars(a) answer_code = "{:SHORTANSWER:=%s~%s}" % (a, alternatives) # {3<weight>:SHORTANSWER:=Berlin#comment~another answer} question = question.replace('..%s....'%nr, answer_code) return """ <!-- question: ...nr... --> <question type="cloze"> <name> <text>%s</text> </name> <questiontext format="html"> <text><![CDATA[Įrašykite, ko trūksta <span style="color:grey">(naudodami minimaliai simbolių/tarpų)</span> <br/> <pre>%s</pre> Kad būtų atspausdinta: <pre>""" % ( title, question ) # pabaigoj CLOZE_TPL_END = """</pre>]]></text> </questiontext> <generalfeedback> <text></text> </generalfeedback> <shuffleanswers>0</shuffleanswers> </question> """ def src_to_GIFT(title, src, f_args=[], f_locals={}, CONVERT2CPP=False, question_text='', lang_code2img='', title_without_hints='', markup_type='markdown'): src = replace_placeholders_to_values(src, f_args, f_locals) src = delete_comments(src, containing='HIDE') # for negatives numbers: tidy minuses -- simplify signs or put brackets src = src.replace('+-', '-').replace('+ -', '-').replace('--', '+').replace('- -', '+') # better use regexp or AST... (someday :P) re_minus_unbraced = re.compile(r'([*/] *?)(-\d+(\.\d+)?)') src = re_minus_unbraced.sub(r'\1(\2)', src) docs_match = re_docs.search(src) # get question text from """docs""" if docs_match: question_text += docs_match.group(1) #~ src = src.replace(docs_match.group(0), docs+'\n') src = src.replace(docs_match.group(0), '' ) #~ src = '\n'.join( src.split('\n')[1:] ) # get rid of first definition line if CONVERT2CPP: src = py2cpp.convert(src) if lang_code2img: name = title_without_hints or title code_highlight(name, lang_code2img, src, LINENOS4IMG=True) src = img_placer('markdown', lang_code2img+'_'+name) else: src = escape_GIFT_spec_chars(src) question_text = escape_GIFT_spec_chars(question_text) src = question_text+'\n\n'+ src src = src.replace('\n', '\n\\n') # GIFT format needs explicit \n title = escape_GIFT_spec_chars(title) return "::%s::[%s]\n\\n%s" %( title, markup_type, src ) # question title, format, and text def escape_CLOZE_answer_chars(txt): # https://docs.moodle.org/22/en/Embedded_Answers_%28Cloze%29_question_type#Importing_CLOZE_questions for char in '*#}': # \ ? txt = txt.replace(char, '\\'+char) if '~' in txt and txt.index('~') > 0: print( "WARNING, tilde (~) better not be in answer, except first position") txt = txt[0]+txt[1:].replace('~', '\\~') if txt.endswith('\\'): txt = txt+' ' #at least in older Moodle versions 2.6 without extra space - it would apply to answer separator (~) char return txt def escape_GIFT_spec_chars(txt, html_escape=False): for char in '=~#{}:': # what about = symbol? txt = txt.replace(char, '\\'+char) # Quotation signs: " can lead to trouble anyhow in both places. Use the HTML entity: &quot; if html_escape: html_escapes = {'<': 'lt', '>':'gt', '#':'#35'} # not to interfere with markdown for char, escape in html_escapes.items(): txt = txt.replace(char, '&'+escape+';') return txt ################################### ######## code 2 img ######### ################################### path2img='output/code2img/html2img/' imgwebdir = 'http://galvosukykla.lt/moodle_code_quiz.img/' def escape_path(txt): lit = 'ąčęėįšųūžĄČĘĖĮŠŲŪŽ' lat = 'aceeisuuzACEEISUUZ' for a, b in zip(lit, lat): txt = txt.replace(a, b) txt = txt.replace('/', '_') \ .replace(' ', '_') \ .replace('\\', '_') \ .replace(':', '_') \ .replace('#', ' ') \ .replace('?', '.') \ .replace('!', '.') \ .replace('"', '_') \ .replace('\'', '_') \ .replace('‘', '`') \ .replace('’', '`') \ #~ .replace('', '') \ return txt def urlescape(txt): return txt.replace(' ', '%20') def code2pygmetshtml(code, lang, linenos=False, inlineCSS=False): # generate highlighted code html (to convert to img) from pygments import highlight if lang == 'py': from pygments.lexers import PythonLexer as Lexer if lang == 'cpp': from pygments.lexers import CppLexer as Lexer from pygments.formatters import HtmlFormatter #~ formatter = HtmlFormatter() formatter = HtmlFormatter(linenos=linenos, noclasses=inlineCSS) #~ formatter = HtmlFormatter(linenos=True, cssclass="source") html = highlight(code, Lexer(), formatter) return html def code_highlight(name, lang, code, linenos=False): from pygments.formatters import HtmlFormatter html = code2pygmetshtml(code, lang, linenos) if conv2IMG: if not os.path.exists(path2img+'pygments_style.css'): with open(path2img+'pygments_style.css', 'w') as f: f.write( HtmlFormatter().get_style_defs('.highlight') ) with open(path2img+lang+'_'+escape_path(name)+'.html', 'w') as f: f.write( """ <!doctype html> <head> <meta charset="utf-8"> <link rel="stylesheet" href="pygments_style.css"> </head> <body> """ + html + "</body>") def img_placer(textformat, img_name ): if textformat == 'html': return '<img src="'+imgwebdir+urlescape(escape_path(img_name))+'.html.png" />' if textformat == 'markdown': return '![alt '+img_name+']('+imgwebdir+urlescape(escape_path(img_name))+'.html.png )'
[ [ 1, 0, 0.0041, 0.0041, 0, 0.66, 0, 540, 0, 1, 0, 0, 540, 0, 0 ], [ 14, 0, 0.0083, 0.0041, 0, 0.66, 0.0526, 679, 3, 2, 0, 0, 821, 10, 1 ], [ 1, 0, 0.0207, 0.0041, 0, ...
[ "import re", "re_docs = re.compile(r'\"\"\"(.*?)\"\"\"', re.DOTALL)", "import py2cpp", "from pygments.lexers import PythonLexer", "lexer = PythonLexer(ensurenl=False)", "def delete_comments(src, containing=''):\n lines = src.split('\\n')\n for nr, line in enumerate(lines):\n for t in lexer.ge...
import json import re file_name = 'a' #'demo' with open(file_name+'.trace.json', 'r') as f: trace_json_txt = f.read() #~ data = json.load ( trace_json_txt ) data = eval ( trace_json_txt ) code = data['code'] linecodes = code.split('\n') trace = data['trace'] print ( '\n### TRACE: ', json.dumps(trace, sort_keys=True, indent=2) ) #~ print ( 'CODE: ', json.dumps(code, sort_keys=True, indent=2) ) print ( '\n### CODE:'); print( code ) ######### plain trace ######## for frame in trace: if frame['event'] == 'step_line': lineno = int( frame['line'] ) print ( lineno, linecodes[lineno-1] ) def not_empty( line ): return line.strip(' \t') and not line.strip(' \t').startswith("#") #is not empty and not comment ########### Construct LOOPS Tree info ####### #~ LOOP_INDENTS = [0] * len(linecodes) #~ LOOP_DEPTHS = [0] * len(linecodes) #~ LOOP_STARTS = [None] * len(linecodes) LOOP_INDENTS = [] # for each line LOOP_DEPTHS = [] # we'll store its LOOP_STARTS = [] # loop dependency def construct_loops_info(): loop_depth = 0 LOOPS_STACK = [ {'indent':0, 'start':'-'} ] # for tree of loops: (indent, start) GET_INSIDELOOP_INDENT = False for nr, line in enumerate(linecodes): line = line.replace('\t', ' ') # replace tabs if not_empty(line): #if line not empty indent = len(line) - len( line.lstrip(' ') ) while indent < LOOPS_STACK[-1]['indent']: # if we return from some loop LOOPS_STACK.pop() loop_depth -= 1 GET_INSIDELOOP_INDENT = False if GET_INSIDELOOP_INDENT: # if we are first line inside the loop -- get indentation LOOP_INDENTS[-1] = LOOPS_STACK[-1]['indent'] = indent GET_INSIDELOOP_INDENT = False linecode = line.lstrip(' ') .replace('\t', ' ').replace('\\', ' ').replace('(', ' ') if linecode.startswith("for ") or linecode.startswith("while "): # TODO migth better be regexp (.*?)\W loop_depth += 1; LOOPS_STACK.append( {'indent': indent+1, 'start': nr} ) # indent+1 is a workaround for our model to deal with oneliner-loop GET_INSIDELOOP_INDENT = True LOOP_INDENTS.append( LOOPS_STACK[-1]['indent'] ) LOOP_DEPTHS.append( loop_depth ) LOOP_STARTS.append( LOOPS_STACK[-1]['start'] ) # line number, where loop starts if True: #~ print("\nDBG construct_loops_info:\n") print("%3d"%nr, "INDENT, DEPTH, START:", "%3d %3d %3s"%(LOOP_INDENTS[-1], LOOP_DEPTHS[-1], LOOP_STARTS[-1]),":", line) construct_loops_info() ########### nested TABLE trace ####### from collections import OrderedDict, defaultdict def order_dicts( d ): ordered = OrderedDict( sorted(d.items(), key=lambda t: t[0]) ) for key, val in ordered.items(): if isinstance( val[0], dict ): val[0] = order_dicts( val[0] ) return ordered from pprint import pprint GO='+'; SKIP=' ' trace_rows = defaultdict(list) trace_stack = [trace_rows] def get_frame_indent(frameno): lineno = int(trace[frameno]['line']) line = linecodes[lineno-1] indent = len(line) - len( line.lstrip(' ') ) return indent def repetition_trace(start_frameno): start_lineno = int(trace[start_frameno]['line']) start_indent = get_frame_indent(start_frameno) lineno = last_lineno = start_lineno frameno = start_frameno looping = False while frameno < len(trace): frame = trace[frameno] lineno = int( frame['line'] ) line = linecodes[lineno-1] linecode = line.lstrip(' ') indent = len(line) - len(linecode) # check for indentation block end if indent < start_indent: break if looping and indent==start_indent and lineno > start_lineno: # some idioms not included: for... else... break # process line if frame['event'] == 'step_line': if lineno > last_lineno+1: for tmp_lineno in range(last_lineno+1, lineno): trace_stack[-1][tmp_lineno].append( SKIP ) #~ trace_stack[-1][lineno].append( GO ) def get_info(): import ast def get_assignment_target(code): # http://hg.python.org/cpython/file/3.3/Lib/ast.py#l89 """ >>> print( get_assignment_target("pinigai = laikas * atlyginimas") ) pinigai """ node = ast.parse(code, mode='exec') if (isinstance(node.body[0], ast.Assign)): assignment = node.body[0] return assignment.targets[0].id # http://eli.thegreenplace.net/2009/11/28/python-internals-working-with-python-asts/ might be of use #~ global linecode nonlocal linecode if '#' in linecode: linecode, comment = linecode.split('#', 1) linecode = linecode.strip() code_chunks = re.split('(\W+)', linecode) code_chunks = [x.strip() for x in code_chunks] start_chunk = code_chunks[0] #~ print ('start_chunk', start_chunk) if code_chunks[0] in ['if', 'elif', 'while']: expr = linecode.split(':')[0] expr = expr[len(start_chunk ):].strip() elif code_chunks[0] in ['for']: #~ expr = code_chunks[1] expr = re.split('\sin[\s\[]', linecode)[0] # TODO: better use ast here... in case in is separated by 'for x in[3, 5]' or other weird cases expr = expr[len(start_chunk ):].strip() elif linecode.endswith(":"): expr = '' elif linecode.startswith("print"): # optionally could track what is printed expr = '' elif linecode == '': expr = None else: expr = get_assignment_target(linecode) or '' # target variable name or None-->'' if expr: value = eval(expr, trace[frameno+1]['globals']) # use globals from next trace -- as the newly assigned vaues will be there else: value = '' if expr is None else GO #~ return "%s@%s" % (indent, frameno) #~ return "%s@%s:%s=%s" % (indent, frameno, expr, value) return value trace_stack[-1][lineno].append( get_info() ) last_lineno = lineno if linecode.startswith('for') \ or linecode.startswith('while'): if lineno > start_lineno: new_loop_trace = defaultdict(list) trace_stack[-1][lineno][-1] = new_loop_trace # replace GO trace_stack.append( new_loop_trace ) frameno = repetition_trace(frameno) # give frameno, and update it after return ;) sub_trace = trace_stack.pop() last_lineno = max( sub_trace.keys() ) #~ print ( "\n Finished branch @ %s..%s " % (lineno, last_lineno) ) #~ pprint ( order_dicts( sub_trace ) ) else: looping = True frameno += 1 return frameno-1 print("\n Result \n") repetition_trace(0) ########### TEST case ############ test_trace_rows = { 1: [GO], 3: [ { 3: [GO,GO,GO,GO,GO,] , 4: [GO,GO,GO,GO,GO,] , 5: [GO,GO,GO,GO,GO,] , 6: [SKIP,SKIP,GO,SKIP,SKIP,] , 7: [GO,GO,GO,GO,GO,] } ], 9: [GO], } # http://docs.python.org/3.3/library/collections.html#ordereddict-examples-and-recipes print("\n Expected \n") pprint ( order_dicts( test_trace_rows ) ) #~ print ( json.dumps( order_dicts( test_trace_rows ), indent=2) ) """#################### s=0 for x in range(1,6): s=s+x if x%3==0: s=0 print(x, s) print ("finish") ######################## 1 s=0 3 for x in range(1,6): 4 s=s+x 5 if x%3==0: 7 print(x, s) 3 for x in range(1,6): 4 s=s+x 5 if x%3==0: 7 print(x, s) 3 for x in range(1,6): 4 s=s+x 5 if x%3==0: 6 s=0 7 print(x, s) 3 for x in range(1,6): 4 s=s+x 5 if x%3==0: 7 print(x, s) 3 for x in range(1,6): 4 s=s+x 5 if x%3==0: 7 print(x, s) 3 for x in range(1,6): 9 print ("finish") ####################### [ ['+'], [ ['+', '+', '+', '+', '+'], ['+', '+', '+', '+', '+'], ['+', '+', '+', '+', '+'], [' ', ' ', '+', ' ', ' '], ['+', '+', '+', '+', '+'] ], ['+'] ] #********** 2 level loop demo *************** s = 5 for x in [1, 3, 2]: print('1st', x) if x > 2: for z in range(2): print('2nd') print('bla') for i in range(x): a = i print('3rd', i) # print('back to 1st') print('end') """
[ [ 1, 0, 0.0033, 0.0033, 0, 0.66, 0, 463, 0, 1, 0, 0, 463, 0, 0 ], [ 1, 0, 0.0066, 0.0033, 0, 0.66, 0.0323, 540, 0, 1, 0, 0, 540, 0, 0 ], [ 14, 0, 0.0133, 0.0033, 0, ...
[ "import json", "import re", "file_name = 'a' #'demo'", " trace_json_txt = f.read()", "data = eval ( trace_json_txt )", "code = data['code']", "linecodes = code.split('\\n')", "trace = data['trace']", "print ( '\\n### TRACE: ', json.dumps(trace, sort_keys=True, indent=2) )", "print ( '\\n### COD...
#! /usr/bin/env python # coding=utf8 class TBaseGraph: def GetVertexCount(self): return 0 def GetAdj(self, vertexNum): return [] def GetWeight(self, fromV, toV): return 0 class TGraphMatrix(TBaseGraph): def __init__(self, matrix): self.Matrix = matrix def GetVertexCount(self): return len(self.Matrix) # Get weights of out edjes of given vertex def GetAdj(self, vertexNum): ret = [] for i in range(len(self.Matrix[vertexNum])): if self.Matrix[vertexNum][i] is not None: ret.insert(len(ret), i) return ret def GetWeight(self, fromV, toV): return self.Matrix[fromV][toV] class TPriorityQueue: def __init__(self, items, priorities, priorityFunc = lambda x, y: (x is not None and y is None) or (x is not None and y is not None and x < y)): self.Elements = [(items[i], priorities[i]) for i in range(len(items))] # копируем элементы к себе self.PriorityFunc = priorityFunc def Pop(self): if not len(self.Elements): return best = 0 for i in range(len(self.Elements)): item, priority = self.Elements[i] bestItem, bestPriority = self.Elements[best] if self.PriorityFunc(priority, bestPriority): best = i bestItem, bestPriority = self.Elements[best] del self.Elements[best] return bestItem def UpdatePriority(self, item, priority): for i in range(len(self.Elements)): it, pr = self.Elements[i] if it == item: self.Elements[i] = (item, priority) return def IsEmpty(self): return len(self.Elements) == 0 def Relax(graph, fromV, toV, d, p, queue): newDistance = d[fromV] + graph.GetWeight(fromV, toV) if d[toV] is None or newDistance < d[toV]: d[toV] = newDistance p[toV] = fromV queue.UpdatePriority(toV, newDistance) def Dijkstra(graph, sourceVertex): vertexCount = graph.GetVertexCount() d = [None for i in range(vertexCount)] p = [None for i in range(vertexCount)] # предшественники d[sourceVertex] = 0 queue = TPriorityQueue([i for i in range(vertexCount)], d) while not queue.IsEmpty(): v = queue.Pop() for u in graph.GetAdj(v): Relax(graph, v, u, d, p, queue) return (d, p) def PrintShortestPath(fromV, toV, shortestLen, shortestPaths): print "{} -> {}: {}: ".format(fromV, toV, shortestLen[toV]) path = [] i = toV while i is not None: path.append(i) i = shortestPaths[i] print "\t", for v in range(len(path) - 1, -1, -1): print "({})".format(path[v]), if path[v] != toV: print " - ", print "" def run_sample(matrix): graph = TGraphMatrix(matrix) for fromV in range(graph.GetVertexCount()): shortestLen, shortestPaths = Dijkstra(graph, fromV) print "Paths from vertex {} with weights:".format(fromV) for i in range(graph.GetVertexCount()): PrintShortestPath(fromV, i, shortestLen, shortestPaths) print "" def run_samples(): matrix = [ [None, 7, 9, None, None, 14], [7, None, 10, 15, None, None], [9, 10, None, 11, None, 2], [None, 15, 11, None, 6, None], [None, None, None, 6, None, 9], [14, None, 2, None, 9, None] ] run_sample(matrix) matrix = [ [None, 7, 9, None, None, 14], [None, None, 10, 15, 10, 5], [99, 10, None, 13, None, 2], [3, 1, 11, None, 8, 7], [None, 6, None, 3, None, 8], [None, None, 1, 18, 6, None] ] run_sample(matrix) def main(): run_samples() if __name__ == "__main__": main()
[ [ 3, 0, 0.0615, 0.0692, 0, 0.66, 0, 996, 0, 3, 0, 0, 0, 0, 0 ], [ 2, 1, 0.0423, 0.0154, 1, 0.78, 0, 313, 0, 1, 1, 0, 0, 0, 0 ], [ 13, 2, 0.0462, 0.0077, 2, 0.84, ...
[ "class TBaseGraph:\n def GetVertexCount(self):\n return 0\n\n def GetAdj(self, vertexNum):\n return []\n\n def GetWeight(self, fromV, toV):", " def GetVertexCount(self):\n return 0", " return 0", " def GetAdj(self, vertexNum):\n return []", " return [...
import numpy as np import numpy.random as nprand import matplotlib.pyplot as plt def spline(x, y, yp1 = 1e30, ypn = 1e30): """Spline method from nrbook. Computes theorical 2nd derivative on every point""" n = len(x) u=range(1,n) y2 = [0]*n if yp1 > 0.99e30: y2[0]= 0.0 u[0]=0.0 else: y2[0] = -0.5 u[0]=(3./(x[1]-x[0]))*((y[1]-y[0])/(x[1]-x[0])-yp1) for i in range(1,n-1): sig=(x[i]-x[i-1])/(x[i+1]-x[i-1]) p=sig*y2[i-1]+2.0 y2[i]=(sig-1.0)/p u[i]=(y[i+1]-y[i])/(x[i+1]-x[i]) - (y[i]-y[i-1])/(x[i]-x[i-1]) u[i]=(6.0*u[i]/(x[i+1]-x[i-1])-sig*u[i-1])/p if ypn > 0.99e30: qn=0.0 un=0.0 else: qn=0.5 un=(3.0/(x[n-1]-x[n-2]))*(ypn-(y[n-1]-y[n-2])/(x[n-1]-x[n-2])) y2[n-1]=(un-qn*u[n-2])/(qn*y2[n-2]+1.0) for k in range(n-2,0,-1): y2[k]=y2[k]*y2[k+1]+u[k] return y2 def splint(xa, ya, y2a, x): """Interpolation with 2nd derivative. Does not guarantee continuity of derivate. Hence, the resulting curve appear angled on some points""" n = len(xa) klo=0 khi=n-1 while (khi-klo > 1): k=(khi+klo) >> 1 if (xa[k] > x): khi=k else: klo=k h=xa[khi]-xa[klo] if h == 0.0: print "Bad xa input to routine splint" a=(xa[khi]-x)/h b=(x-xa[klo])/h return a*ya[klo]+b*ya[khi]+((a*a*a-a)*y2a[klo]+(b*b*b-b)*y2a[khi])*(h*h)/6.0 def interp(xa,ya,ypa,x): """Computes cubic interpolation guaranteeing continuity of derivative. Smoother than nrbook interpolation !""" n = len(xa) klo=0 khi=n-1 while (khi-klo > 1): k=(khi+klo) >> 1 if (xa[k] > x): khi=k else: klo=k h = float(xa[khi] - xa[klo]) a = 2 * ya[klo] - 2 * ya[khi] + ypa[klo] * h + ypa[khi] * h b = ((ypa[khi] - ypa[klo]) * h - 3 * a)/2. x = (x - xa[klo]) / h return ya[klo] + x * ( ypa[klo] * h + x * ( b + x * a ) ) def make_function(xa, ya, yp1 = 1e30, ypn = 1e30): """Computes theorical derivates on every point (x y)""" n = len(xa) u = range(n) if yp1 > 0.99e30: u[0] = (ya[1] - ya[0]) / ( xa[1] - xa[0] ) else: u[0] = yp1 if ypn > 0.99e30: u[n-1] = (ya[n-1] - ya[n-2]) / ( xa[n-1] - xa[n-2] ) else: u[n-1] = yp1 for i in range(1,n-1): u[i] = ((ya[i+1] - ya[i]) / ( xa[i+1] - xa[i] ) + (ya[i] - ya[i-1])/ ( xa[i] - xa[i-1] ))/2. return lambda x: interp(xa, ya, u, x) def make_function_der(xa, ya, yp1 = 1e30, ypn = 1e30): """Computes theorical derivates on every point (x y)""" n = len(xa) u = range(n) if yp1 > 0.99e30: u[0] = (ya[1] - ya[0]) / ( xa[1] - xa[0] ) else: u[0] = yp1 if ypn > 0.99e30: u[n-1] = (ya[n-1] - ya[n-2]) / ( xa[n-1] - xa[n-2] ) else: u[n-1] = yp1 for i in range(1,n-1): u[i] = ((ya[i+1] - ya[i]) / ( xa[i+1] - xa[i] ) + (ya[i] - ya[i-1])/ ( xa[i] - xa[i-1] ))/2. return lambda x: interp_der(xa, ya, u, x) def interp_der(xa,ya,ypa,x): """Computes derivate of interpolation. Useful to avoid approximation on next part""" n = len(xa) klo=0 khi=n-1 while (khi-klo > 1): k=(khi+klo) >> 1 if (xa[k] > x): khi=k else: klo=k h = float(xa[khi] - xa[klo]) a = 2 * ya[klo] - 2 * ya[khi] + ypa[klo] * h + ypa[khi] * h b = ((ypa[khi] - ypa[klo]) * h - 3 * a)/2. x = (x - xa[klo]) / h return ypa[klo] * h + x * ( 2 * b + 3 * x * a ) def plot(f, a, b): v = [] fv = [] steps = 256. for i in np.arange(a, b + (b-a)/steps, (b - a)/steps): fv.append(f(i)) #f(x) plt.plot(np.arange(a, b + (b-a)/steps, (b - a)/steps), fv) if __name__ == "__main__": ya = [1.0, 1.1, 0.9, 0.8, 1.02, 1.1] xa = np.arange(0,len(ya) * 2, 2) steps = 32 splits = len(ya)-1 v = [] for i in range(2*splits * steps+1): x = i / float(steps) #x v.append(x) fv = [] ffv = [] #Nrbook interpolation y2a = spline(xa, ya) for i in range(2*splits * steps+1): fv.append(splint(xa, ya, y2a, v[i])) #f(x) for i in range(2*splits * steps): ffv.append((fv[i+1]-fv[i])*steps) #f'(x) ffv.append(fv[len(fv)-1]) #f'(x) plt.plot(v, fv) #plt.plot(v, ffv) #plt.show() #Home-made, smoother than nrbook ! plot(make_function(xa, ya), xa[0], xa[len(xa) - 1]) #plot(make_function_der(xa, ya), xa[0], xa[len(xa) - 1]) plt.show()
[ [ 1, 0, 0.0062, 0.0062, 0, 0.66, 0, 954, 0, 1, 0, 0, 954, 0, 0 ], [ 1, 0, 0.0124, 0.0062, 0, 0.66, 0.1, 181, 0, 1, 0, 0, 181, 0, 0 ], [ 1, 0, 0.0186, 0.0062, 0, 0.6...
[ "import numpy as np", "import numpy.random as nprand", "import matplotlib.pyplot as plt", "def spline(x, y, yp1 = 1e30, ypn = 1e30):\n\t\"\"\"Spline method from nrbook. Computes theorical 2nd derivative on every point\"\"\"\n\tn = len(x)\n\tu=range(1,n)\n\ty2 = [0]*n\n\tif yp1 > 0.99e30:\n\t\ty2[0]= 0.0\n\t\t...
import numpy as np import re # regexp import matplotlib.pyplot as plt import splines as sp ################################################################ # Airfoil : load profile of a wing # # Reads a file whose lines contain coordinates of points, # separated by an empty line. # Every line not containing a couple of floats is discarded. # Returns a couple constitued of the list of points of the # extrados and the intrados. def load_foil(file): f = open(file, 'r') matchline = lambda line: re.match(r"\s*([\d\.-]+)\s*([\d\.-]+)", line) extra = []; intra = [] rextra = False; rintra = False for line in f: m = matchline(line) if (m != None) and not(rextra): rextra = True if (m != None) and rextra and not(rintra): extra.append(m.groups()) if (m != None) and rextra and rintra: intra.append(m.groups()) if (m == None) and rextra: rintra = True ex = np.array(map(lambda t: float(t[0]),extra)) ey = np.array(map(lambda t: float(t[1]),extra)) ix = np.array(map(lambda t: float(t[0]),intra)) iy = np.array(map(lambda t: float(t[1]),intra)) exx = ix[0:ex[0]] exy = iy[0:ey[0]] inx = ix[ex[0]:] iny = iy[ey[0]:] return(exx,exy,inx,iny) (ex,ey,ix,iy) = load_foil("../doc/boe106.dat") plt.plot(ex, ey) plt.plot(ix, iy) plt.show() sp.plot(sp.make_function(ex,ey), ex[0], ex[len(ex) - 1]) sp.plot(sp.make_function(ix,iy), ix[0], ix[len(ix) - 1]) plt.show()
[ [ 1, 0, 0.0213, 0.0213, 0, 0.66, 0, 954, 0, 1, 0, 0, 954, 0, 0 ], [ 1, 0, 0.0426, 0.0213, 0, 0.66, 0.0909, 540, 0, 1, 0, 0, 540, 0, 0 ], [ 1, 0, 0.0638, 0.0213, 0, ...
[ "import numpy as np", "import re # regexp", "import matplotlib.pyplot as plt", "import splines as sp", "def load_foil(file):\n f = open(file, 'r')\n matchline = lambda line: re.match(r\"\\s*([\\d\\.-]+)\\s*([\\d\\.-]+)\", line)\n extra = []; intra = []\n rextra = False; rintra = False\n f...
import numpy as np import splines as sp import matplotlib.pyplot as plt import time import numpy.random as nprand def Left(f, a, b): return (b - a) * f(a) def Middle(f, a, b): return (b - a) * f( (a+b)/2. ) def Middle_raf(f, a, b, epsilon, val = None): bma = b-a if (val == None): val = bma * f( (a+b)/2. ) val2 = bma * f(a+bma/4.) val3 = bma * f(a+0.75*bma) nextval = (val + val2 + val3) / 3. if (abs(val-nextval) > epsilon): step = bma / 3. val2 = Middle_raf(f, a, a+step,epsilon, val2/3.) val = Middle_raf(f, a+step, b-step,epsilon, val/3.) val3 = Middle_raf(f, b-step, b,epsilon, val3/3.) nextval = val + val2 + val3 return nextval def Simson(f, a, b): return (b - a) / 6. * ( f(a) + 4 * f( (a+b)/2. ) + f(b) ) def Simson_raf(f, a, b, epsilon, valLeft = None, valRight = None): bma = b-a if (valLeft == None): valLeft = bma * f(a) if (valRight == None): valRight = bma * f(b) val = bma * f(a+bma/2.) nextval = ( val * 4 + valLeft + valRight ) / 6. if (abs(valLeft+valRight-2*nextval) > 2*epsilon): valLeft = Simson_raf(f, a, a+bma/2.,epsilon, valLeft/2., val/2. ) valRight = Simson_raf(f, a+bma/2., b,epsilon, val/2., valRight/2.) nextval = valLeft + valRight return nextval def Integr(f, a, b, n = 100, methode = Simson): step = (b-a)/float(n) acc = 0 for i in range(n): acc += methode(f, a + i*step, a + i*step + step) return acc def Integr_raf(f, a, b, n = 20, epsilon=1e-8, methode = Middle_raf): step = (b-a)/float(n) acc = 0 for i in range(n): acc += methode(f, a + i*step, a + i*step + step, epsilon) return acc def Length(fp, a, b, n = 100): return Integr(lambda x: np.sqrt(1 + fp(x) * fp(x)), a, b, n) def monte_carlo_integration(f, a, b, n): "integrates POSITIVE FUNCTION using Monte-Carlo method" maxi = 0. res = 0. for i in range(n+1): var = f(a + b * float(i+1)/n) if(maxi < var): maxi = var V = (b - a) * maxi # maximal and simple aire for i in range(n): aleax = (b-a) * nprand.rand() + a aleay = maxi * nprand.rand() if(aleay <= maxi): res += V/n * f(aleax) return res def monte_carlo_plot(n): v = [] for i in range(n): v.append(monte_carlo_integration(lambda x: x**3 - 4*x**2 + x , 0, 1, i*10+1)) plt.plot(range(n), v) plt.title("evolution of monte-carlo accuracy for integrate of x^3 - 4*x^2 + x") if __name__ == "__main__": # print Integr(lambda x: x*x, 0., 2., 40, Middle) # print Integr(lambda x: x, 0., 2., 10, Simson) ya_blue = [1.5, -1.5, 1.5, -1.5, 1.5, -1.5] ya_green = [-1, 1, -1, 1, -1, 1] ya_red = [-0.1, 0.1, -0.1, 0.1, -0.1, 0.1] xa = range(len(ya_blue)) steps = 32 splits = len(ya_blue)-1 blue = sp.make_function(xa, ya_blue) green = sp.make_function(xa, ya_green) red = sp.make_function(xa, ya_red) f = lambda x: x**5 imid = [] isim = [] isim_r = [] imont = [] prevsim = 0. prevsim_r = 0. prevmid = 0. prevmont = 0. cur = 0. # Cauchy convergence : for i in range(1, 100): cur = Integr(f, 0., 10., i, Middle) imid.append(abs(cur-prevmid)) prevmid = cur for i in range(2, 100, 2): cur = Integr(f, 0., 10., i/2) isim.append(abs(cur-prevsim)) prevsim = cur # for i in range(2, 10, 2): # cur = Integr_raf(f, 0., 10., i) # isim_r.append(abs(cur-prevsim_r)) # prevsim_r = cur for i in range(1, 2000): cur = monte_carlo_integration(f , 0., 10., i) imont.append(abs(cur-prevmont)) prevmont = cur #p1 = plt.plot(range(2,100,2),isim,label="Simson") # p2 = plt.plot(range(1,100),imid,label="Middle point") p3 = plt.plot(range(1,2000),imont,label="Monte Carlo") plt.title("Convergence speed") plt.semilogy() plt.savefig("Integration") plt.show() print "Curves length :" ypa_blue = sp.make_function_der(xa, ya_blue) ypa_green = sp.make_function_der(xa, ya_green) ypa_red = sp.make_function_der(xa, ya_red) print "Blue:",Length(ypa_blue, 0, splits, steps) print "Green:",Length(ypa_green, 0, splits, steps) print "Red:",Length(ypa_red, 0, splits, steps) plt.axis('equal') sp.plot(blue,0,splits) sp.plot(green,0,splits) sp.plot(red,0,splits) plt.show()
[ [ 1, 0, 0.0065, 0.0065, 0, 0.66, 0, 954, 0, 1, 0, 0, 954, 0, 0 ], [ 1, 0, 0.013, 0.0065, 0, 0.66, 0.0667, 774, 0, 1, 0, 0, 774, 0, 0 ], [ 1, 0, 0.0195, 0.0065, 0, 0...
[ "import numpy as np", "import splines as sp", "import matplotlib.pyplot as plt", "import time", "import numpy.random as nprand", "def Left(f, a, b):\n\treturn (b - a) * f(a)", "\treturn (b - a) * f(a)", "def Middle(f, a, b):\n\treturn (b - a) * f( (a+b)/2. )", "\treturn (b - a) * f( (a+b)/2. )", "...
import numpy as np import pylab as pl import splines as sp from integration import Length from load_foil import load_foil def f_lambda(f, Lambda, h): "Returns the function f_lambda, with h = hmin or hmax" return lambda x: (1 - Lambda) * f(x) + 3 * Lambda * h def show_colored(f, a, b, colour = (0,0,1), width = 4): "Create the graph of a function f on the interval [a,b], in color" v = [] fv = [] steps = 256. for i in np.arange(a, b + (b-a)/steps, (b - a)/steps): fv.append(f(i)) pl.plot(np.arange(a, b + (b-a)/steps, (b - a)/steps), fv, color = colour, linewidth = width) def get_color(Pmin, Pmax, P): "For a given pressure, gives the right color to use" color = ((1,1,1), (1,1,0), (1,204/255.,102/255.), (1,153/255.,0), (1,0,0), (204/255.,0,0), (153/255.,0,0), (102/255.,0,0), (51/255.,0,0), (0,0,0)) pitch = (Pmax**2 - Pmin**2) / 100 # 100 = square of the number of colors P = P**2 - Pmin**2 if (0<=P<=pitch): return color[9] elif (pitch < P <= 2* pitch): return color[8] elif (2 * pitch < P <= 3* pitch): return color[7] elif (3 * pitch < P <= 4* pitch): return color[6] elif (4 * pitch < P <= 5 * pitch): return color[5] elif (5* pitch < P <= 6 * pitch): return color[4] elif (6 * pitch < P <= 7 * pitch): return color[3] elif (7 * pitch < P <= 8 * pitch): return color[2] elif (8 * pitch < P <= 9 * pitch): return color[1] else: return color[0] def pressure_mapping(input, pitch = 0.01): "Maps the pressure around a wing given by input (a .dat file)" pl.clf() (ex,ey,ix,iy) = load_foil(input) hmin = np.min(iy) hmax = np.max(ey) fup = sp.make_function(ex,ey) flow = sp.make_function(ix,iy) precision_length = np.arange(0,1,0.01) Pmax = Length(sp.make_function_der(ex,ey),0.,1.,100) Pmin = Length(sp.make_function_der(np.arange(0,1,0.01), map(f_lambda(fup,1,hmax),precision_length)), 0., 1., 100) for i in np.arange(1e-2 , 1 , pitch): # over the extrados, 1e-2 is to avoid superposition of the wing and the pressure f = f_lambda(fup , i ,hmax) v = Length(sp.make_function_der(np.arange(0,1,0.01), map(f,precision_length)) ,0.,1.,100) show_colored(f , ex[0],ex[len(ex) - 1], get_color(Pmin, Pmax, v**2)) for i in np.arange(1e-2, 1 , pitch): # under the intrados f = f_lambda(flow , i ,hmin) v = Length(sp.make_function_der(np.arange(0,1,0.01), map(f,np.arange(0,1,0.01))) ,0.,1.,100) show_colored(f, ix[0], ix[len(ix) - 1], get_color(Pmin,Pmax, v**2)) show_colored(fup, ex[0], ex[len(ex) - 1],'g',2) show_colored(flow, ix[0], ix[len(ix) -1],'g',2) print "Pressure mapping done" pl.show() pressure_mapping("../doc/clarkx.dat")
[ [ 1, 0, 0.0125, 0.0125, 0, 0.66, 0, 954, 0, 1, 0, 0, 954, 0, 0 ], [ 1, 0, 0.025, 0.0125, 0, 0.66, 0.1111, 735, 0, 1, 0, 0, 735, 0, 0 ], [ 1, 0, 0.0375, 0.0125, 0, 0...
[ "import numpy as np", "import pylab as pl", "import splines as sp", "from integration import Length", "from load_foil import load_foil", "def f_lambda(f, Lambda, h):\n\t\"Returns the function f_lambda, with h = hmin or hmax\"\n\treturn lambda x: (1 - Lambda) * f(x) + 3 * Lambda * h", "\t\"Returns the fu...
__author__ = 'grigory' import sympy as smp import copy import scipy as sc def ch(alpha, index, is_plus): beta = copy.copy(alpha) if is_plus: if beta[2 * index + 1] > 0: beta[2 * index + 1] -= 1 beta[2 * index] += 1 return beta else: if beta[2 * index] > 0: beta[2 * index + 1] += 1 beta[2 * index] -= 1 return beta return [] def minus(alpha, beta): gamma = [] for i in range(len(alpha)): gamma += [alpha[i] - beta[i]] return gamma def get_all_less(alpha): if len(alpha) == 1: return [[i] for i in range(alpha[0] + 1)] else: res = [] beta = get_all_less(alpha[1:]) for element in range(alpha[0] + 1): res += [[element] + b for b in beta] return res ''' iter = iteration number ''' def next_iteration_for_alpha_r(pols, iter, variables, variable, k, d, A, alpha): # 1st sum sum1 = smp.sympify("0") if tuple([variable] + alpha) in pols[iter - 1]: pol = pols[iter - 1][tuple([variable] + alpha)] for i in range(k): Au = "(" for j in range(d): Au += str(A[i][j]) + "*" + variables[j] + "+" Au = Au[:-1] Au += ")" sum1 += smp.diff(pol, variables[i]) * smp.sympify(Au) #2nd sum sum2 = smp.sympify("0") betas = get_all_less(alpha) for beta in betas: for i in range(k): if tuple([variable] + beta) in pols[iter - 1]: if tuple([variables[i]] + minus(alpha, beta)) in pols[0]: pol1 = pols[iter - 1][tuple([variable] + beta)] pol2 = pols[0][tuple([variables[i]] + minus(alpha, beta))] sum2 += smp.diff(pol1, variables[i]) * smp.sympify(pol2) #3rd sum sum3 = smp.sympify("0") for i in range(0, d - k): Au = "(" for j in range(d): Au += str(A[k + i][j]) + "*" + variables[j] + "+" Au = Au[:-1] Au += ")" if tuple([variable] + ch(alpha, i, True)) in pols[iter - 1]: beta = ch(alpha, i, True) pol = pols[iter - 1][tuple([variable] + beta)] sum3 += smp.sympify(str(beta[2 * i])) * smp.sympify(pol) * smp.sympify(Au) if tuple([variable] + ch(alpha, i, False)) in pols[iter - 1]: beta = ch(alpha, i, False) pol = pols[iter - 1][tuple([variable] + beta)] sum3 -= smp.sympify(str(beta[2 * i + 1])) * smp.sympify(pol) * smp.sympify(Au) #4th sum sum4 = smp.sympify("0") for beta in betas: for i in range(d - k): if tuple([variable] + ch(beta, i, True)) in pols[iter - 1]: pol1 = pols[iter - 1][tuple([variable] + ch(beta, i, True))] if tuple([variables[k + i]] + minus(alpha, beta)) in pols[0]: pol2 = pols[0][tuple([variables[k + i]] + minus(alpha, beta))] sum4 += smp.sympify(pol1) * smp.sympify(pol2) * smp.sympify(ch(beta, i, True)[2 * i]) if tuple([variable] + ch(beta, i, False)) in pols[iter - 1]: pol1 = pols[iter - 1][tuple([variable] + ch(beta, i, False))] if tuple([variables[k + i]] + minus(alpha, beta)) in pols[0]: pol2 = pols[0][tuple([variables[k + i]] + minus(alpha, beta))] sum4 -= smp.sympify(pol1) * smp.sympify(pol2) * smp.sympify(ch(beta, i, False)[2 * i + 1]) return sum1 + sum2 + sum3 + sum4 def next_iteration_for_system(pols, iteration, variables, k, d, A, max_initial_degs): topdeg = [] for i in range(len(max_initial_degs)): topdeg += [max_initial_degs[i] * (iteration + 1)] possible_degs = get_all_less(topdeg) polsForIteration = dict([]) for possible_deg in possible_degs: for variable in variables: polsForIteration[tuple([variable] + possible_deg)] = next_iteration_for_alpha_r(pols, iteration, variables, variable, k, d, A, possible_deg) pols += [polsForIteration] return pols def matlab_f_n(pols, n, variables): pol = pols[n] res = dict([]) for (t, p) in pol.iteritems(): if str(p) != "0": if t[0] not in res: res[t[0]] = "" res[t[0]] += "(" + str(p) + ")*" + form_matlab_line(t, variables) + "+" for v in variables: res[v] = res[v][:-1] res[v] = res[v].replace("**", "^") return res def matlab_u_n(variables, u_n, f_n, A): res = dict([]) for i in range(len(variables)): v = variables[i] res[v] = "-(" for j in range(len(variables)): res[v] += "(" + str(A[i][j]) + ")*" + u_n[variables[j]] + "+" res[v] = res[v][:-1] res[v] += ")-" res[v] += f_n[v] return res # assume A to be diagonal def matlab_s_n(n, delta, k, q, A): s_n = [] for qq in range(q): s = 0 s += ((-1) ** (n + 1)) * ((-float(A[qq][qq]) + k) ** (-n - 1)) m = sc.exp(-delta * (float(A[qq][qq]) + k)) for nn in range(n + 1): s += ((-1) ** nn) * (delta ** (n - nn)) * ((-float(A[qq][qq]) + k) ** (-nn - 1)) * m s_n += [s] return s_n def form_matlab_line(t, variables): d = len(variables) k = d - (len(t) - 1) / 2 res = "" for i in range(d - k): res += "(sin(" + variables[k + i] + "))^(" + str(t[2 * (i + 1) - 1]) + ")*(cos(" + variables[ k + i] + "))^(" + str(t[2 * (i + 1)]) + ")*" res = res[:-1] return res def write_to_m_file(pols, iteration, variables, q, k, delta, A): f_ns = [] u_0 = dict([]) for v in variables: u_0[v] = v u_ns = [u_0] s_ns = [] for i in range(iteration + 1): f_ns += [matlab_f_n(pols, i, variables)] for i in range(1, iteration + 1): u_ns += [matlab_u_n(variables, u_ns[i - 1], f_ns[i - 1], A)] for i in range(iteration + 1): s_ns += [matlab_s_n(i, delta, k, q, A)] res = dict([]) for i in range(q): res[variables[i]] = variables[i] + "-(" for j in range(iteration + 1): res[variables[i]] += "(" + str(s_ns[j][i]) + ")*(" + f_ns[j][variables[i]] + "-" + str(k) + "*(" + u_ns[j][ variables[i]] + ")) + " res[variables[i]] = res[variables[i]][:-2] res[variables[i]] = res[variables[i]].replace("**", "^") final_str = "" for i in range(q): final_str += "(" + res[variables[i]] + ")) + " final_str = final_str[:-2] fl = open("polynom" + str(iteration) + ".m", "w") line = "function answer = polynom" + str(iteration) + "(" for v in variables: line += v line += ", " line = line[:-2] line += ")\n" fl.write(line) line = "answer = " line += str(smp.simplify(smp.sympify(final_str))).replace("**", "^") line += ";\n" fl.write(line) fl.write("end\n") fl.close() def main(): #open config file f = open("config", "r") #read variables name line = f.next() variables = line.strip().split(" ") d = len(variables) #read k line = f.next() k = int(line.strip()) #read matrix A A = [] for i in range(d): a = f.next().strip().split(" ") A += [a] #maxdegrees for possible values estimation max_initial_degs = [1] * (2 * (d - k)) #deal with lines pols = [] polsForIteration = dict([]) for line in f: line = line.strip() chunks = line.split(" ") for i in range(1, len(chunks) - 1): chunks[i] = int(chunks[i]) if max_initial_degs[i - 1] < chunks[i]: max_initial_degs[i - 1] = chunks[i] polsForIteration[tuple(chunks[:-1])] = chunks[-1] pols += [polsForIteration] f.close() for xxx in pols: print xxx for iteration in range(7): pols = next_iteration_for_system(pols, iteration + 1, variables, k, d, A, max_initial_degs) print(str(iteration) + " completed") #print matlab_f_n(pols, 2, variables) for iteration in range(8): write_to_m_file(pols, iteration, variables, 2, 10, 0.001, A) print str(iteration) + " file done" main()
[ [ 14, 0, 0.0038, 0.0038, 0, 0.66, 0, 777, 1, 0, 0, 0, 0, 3, 0 ], [ 1, 0, 0.0113, 0.0038, 0, 0.66, 0.0625, 533, 0, 1, 0, 0, 533, 0, 0 ], [ 1, 0, 0.015, 0.0038, 0, 0....
[ "__author__ = 'grigory'", "import sympy as smp", "import copy", "import scipy as sc", "def ch(alpha, index, is_plus):\n beta = copy.copy(alpha)\n if is_plus:\n if beta[2 * index + 1] > 0:\n beta[2 * index + 1] -= 1\n beta[2 * index] += 1\n return beta\n else:...
import numpy as np import pylab as plt import matplotlib.pyplot as mp ### Methodes de choix du pas ### def step_euler(y, t, h, f): return h*f(y,t) + y def step_ptmilieu(y, t, h, f): return y + h*f( y + (h/2.) * f(y,t) , t+(h/2.) ) def step_heun(y,t,h,f): return y + (h/2.) * ( f(y,t) + f( y + h*f(y,t) , t+h )) def step_RK4(y, t, h, f): k1 = f(y,t) k2 = f(y + (h/2.)*k1, t + h/2.) k3 = f(y + (h/2.)*k2, t + h/2.) k4 = f(y + h*k3 , t+h) return y + (h/6.)*(k1 + 2*k2 + 2*k3 + k4) ### Methodes du resolution ### def meth_n_step(Yg,N,h,meth): t0 = Yg[0][0] y0 = Yg[0][1] sol=[y0] for i in range (0,N): ti = t0+i*h yi = sol[i] sol.append(meth(yi,ti,h,Yg[1])) return sol def meth_epsilon(Yg, tf, eps, meth): t0 = Yg[0][0] y0 = Yg[0][1] f = Yg[1] i = 1 h = np.linalg.norm(abs(tf-t0)) tmp = np.linalg.norm(y0) sol = meth_n_step(Yg,1,h,meth) while(abs((sol[len(sol)-1]-tmp)) > eps): tmp = sol[len(sol)-1] i = i + 1 h = abs(tf-t0)/i sol = meth_n_step(Yg,i,h,meth) return sol ### Champs de vecteurs ### def champs_vecteurs(eq,ymin=0,ymax=2): f = eq[1] x = np.arange(-2., 2., 0.2) y = np.arange(0., 4., 0.2) X = [] Y = [] fx = [] fy = [] for i in range(len(x)): for j in range(len(y)): a = f(x[i],y[j]) fy = fy + [a/(abs(a)*((np.sqrt((1./a)**2+1))))] fx = fx + [1./((np.sqrt(a**2+1)))] X = X + [x[i]] Y = Y + [y[j]] mp.clf() mp.ylim(ymin,ymax) mp.quiver(X,Y,fx,fy) x = np.arange(-2., 2., 0.1) mp.plot(x,meth_n_step(eq, 39, 0.1, step_RK4), label='Solution') mp.title('Champs des vecteurs tangents') mp.legend() mp.show() if __name__ == "__main__": print "nothing to do here"
[ [ 1, 0, 0.0122, 0.0122, 0, 0.66, 0, 954, 0, 1, 0, 0, 954, 0, 0 ], [ 1, 0, 0.0244, 0.0122, 0, 0.66, 0.1, 735, 0, 1, 0, 0, 735, 0, 0 ], [ 1, 0, 0.0366, 0.0122, 0, 0.6...
[ "import numpy as np", "import pylab as plt", "import matplotlib.pyplot as mp", "def step_euler(y, t, h, f):\n return h*f(y,t) + y", " return h*f(y,t) + y", "def step_ptmilieu(y, t, h, f):\n return y + h*f( y + (h/2.) * f(y,t) , t+(h/2.) )", " return y + h*f( y + (h/2.) * f(y,t) , t+(h/2.) )"...
#-*- coding=utf-8 -*- import numpy as np import matplotlib.pyplot as mp from matplotlib.animation import ArtistAnimation import partie1_methodes as p1 def SolveMaillon1(theta, w, g, l, N, times, meth): "Fonction resolvant le problème du pendule simple" h = times/N eq = [(0.,[theta, w]),lambda X,t:np.array([X[1],(-g * np.sin(X[0]))/l])] return p1.meth_n_step(eq,N, h,p1.step_euler) def PlotMaillon1(sol, N, times): "Fonction traçant la vitesse angulaire et theta en fonction du temps" h = times/N tms = np.arange(0.,times+h,h) sol_theta = map(lambda t : t[0], sol) sol_w = map(lambda t : t[1], sol) mp.clf() mp.plot(tms, sol_theta) mp.plot(tms, sol_w) mp.plot(tms,np.zeros(len(tms)),'k') mp.title("Variation de l'angle et de la vitesse du pendule a 1 maillon") mp.legend(("Angle theta","Vitesse angulaire")) mp.xlabel("Temps t") mp.ylabel("Angle theta") mp.savefig("../img/VariationTheta+VitesseMaillon1") mp.show() def PlotTrajMaillon1(sol, l): "Fonction traçant la trajectoire du pendule simple" sol_theta = map(lambda t : t[0], sol) x = l*np.sin(sol_theta) y = -l*np.cos(sol_theta) mp.clf() mp.plot(0,0,marker='o', color='r', ls='') mp.plot(x, y) mp.plot([0,1/2.],[0,np.sqrt(3)/2.],'k') mp.title("Trajectoire du pendule a 1 maillon") mp.legend(("Trajectoire extremitee du pendule")) mp.xlabel("Temps t") mp.ylabel("Angle theta") mp.savefig("../img/TrajectoireMaillon1") mp.show() def Maillon1(): "Fonction resolvant puis traçant le problème du pendule simple" g = 9.8 l = 1. N = 1240 times = 20. theta = np.pi/4 w = 0. meth = p1.step_euler sol = SolveMaillon1(theta, w, g, l, N, times, meth) PlotMaillon1(sol, N, times) PlotTrajMaillon1(sol, l) def FreqMaillon1(theta): "Fonction determinant la fréquence d'oscilation du pendule simple" g = 9.8 l = 1. N = 1240 times = 20. h = times/N eq = [(0.,[theta,0.]), lambda X,t: np.array([X[1],(-g * np.sin(X[0]))/l])] x = np.arange(0.,times+h,h) sol = p1.meth_n_step(eq, N, h, p1.step_RK4) sol_theta = map(lambda t : t[0], sol) sol_w = map(lambda t : t[1], sol) tps = 0. Ts = [] for i in range(0, len(sol_w)-1): if ((sol_w[i] < 0) and (sol_w[i+1] >= 0)): Ts.append(tps) tps += h T = (Ts[len(Ts)-1]-Ts[0]) / len(Ts) return 1/T def FrecTraceMaillon1(): "Fonction traçant le frequence d'oscilation d'un pendule simple pour differents theta0" theta = np.arange(-2*np.pi/3,2*np.pi/3,0.2) y = [] for i in range(len(theta)): y.append(FreqMaillon1(theta[i])) mp.plot(theta, y, linewidth=1.0) mp.plot([theta[0],theta[len(theta)-1]],[np.sqrt(9.8/1.0)/(2*np.pi),np.sqrt(9.8/1.0)/(2*np.pi)]) mp.xlabel("Angle initial") mp.ylabel("Frequence du pendule") mp.title("Frequence du pendule a 1 maillon") mp.savefig("../img/FrequenceMaillon1") mp.show() ## DEUX MAILLONS ## def SolveMaillon2(theta1,theta2,w1,w2,g,l1,l2,m1,m2,N,times, meth): "Fonction resolvant le problème du pendule à deux maillons" h = times/N eq = [(0.,[theta1, w1, theta2, w2]), lambda X,T: np.array([X[1],(-g*(2*m1+m2)*np.sin(X[0])-m2*g*np.sin(X[0]-2*X[2])-2*np.sin(X[0]-X[2])*m2*(l2*(X[3]**2)+(X[1]**2)*l1*np.cos(X[0]-X[2])))/(l1*(2*m1 + m2 - m2*np.cos(2*X[0]-2*X[2]))), X[3], (2*np.sin(X[0]-X[2])*((X[1]**2)*l1*(m1+m2) + g*(m1+m2)*np.cos(X[0]) + (X[3]**2)*l2*m2*np.cos(X[0]-X[2]))) / (l2*(2*m1 + m2 - m2*np.cos(2*X[0]-2*X[2]))) ])] return p1.meth_n_step(eq, N, h, p1.step_RK4) def PlotMaillon2(sol, N, times): "Fonction tracant l'angle et la vitesse angulaire de theta1 et theta2 en fonction du temps" h = times/N tms = np.arange(0.,times+h,h) sol_theta1 = map(lambda t : t[0], sol) sol_w1 = map(lambda t : t[1], sol) sol_theta2 = map(lambda t : t[2], sol) sol_w2 = map(lambda t : t[3], sol) mp.clf() mp.plot(tms, sol_theta1) mp.plot(tms, sol_theta2) #mp.plot(tms, sol_w1) #mp.plot(tms, sol_w2) mp.legend(("Angle theta1","Angle theta2","Vitesse angulaire 1","Vitesse angulaire 2")) mp.title("Modelisation du pendule a 2 maillons") mp.xlabel("Temps t") mp.ylabel("Angle theta") mp.savefig("../img/Maillon2Angle+Vitesse") mp.show() def PlotTrajMaillon2(sol, l1, l2): "Fonction traçant la trajectoire du pendule à deux maillons" sol_theta1 = map(lambda t : t[0], sol) sol_theta2 = map(lambda t : t[2], sol) x1 = l1*np.sin(sol_theta1) y1 = -l1*np.cos(sol_theta1) x2 = l2*np.sin(sol_theta2)+x1 y2 = -l2*np.cos(sol_theta2)+y1 mp.clf() mp.plot(0,0,marker='o', color='r', ls='') mp.plot(x1, y1) mp.plot(x2, y2) mp.legend(("Trajectoire extremitee du pendule")) mp.title("Trajectoire du pendule a 2 maillons") mp.xlabel("Temps t") mp.ylabel("Angle theta") mp.savefig("../img/TrajectoireMaillon2") mp.show() def AnimatonTrajMaillon(sol, l1, l2, N, times): "Fonction animant un ensemble de points correpondants ici au pendule." #Attention à ne pas quiter la fenetre d'animation avant la fin sous peine d'avoir une erreur. sol_theta1 = map(lambda t : t[0], sol) sol_theta2 = map(lambda t : t[2], sol) x1 = l1*np.sin(sol_theta1) y1 = -l1*np.cos(sol_theta1) x2 = l2*np.sin(sol_theta2)+x1 y2 = -l2*np.cos(sol_theta2)+y1 fig = mp.figure() ax = fig.add_subplot(111) ax.set_xlim(-20, 20) ax.set_ylim(-20,10) images = [] for i in range(0, len(sol_theta2)): line = ax.plot([0, x1[i]],[0, y1[i]], x2[0:i],y2[0:i], [x1[i], x2[i]],[y1[i], y2[i]], '-', color='b') images.append((line)) line_anim = ArtistAnimation(fig, images, interval=20, repeat=False) #line_anim.save('doublemaillon.mp4') mp.show() def Maillon2Chaos(): "Fonction resolvant le problème du pendule double et l'affichant, état chaotique" g = 9.8 l1 = 10. l2 = 10. m1 = 1. m2 = 1. N = 300 times = 40. theta1 = np.pi/2. theta2 = np.pi/3. w1 = np.sqrt(g/l2) w2 = 0. sol = SolveMaillon2(theta1, theta2, w1, w2, g, l1, l2, m1, m2, N, times, p1.step_RK4) PlotMaillon2(sol, N, times) PlotTrajMaillon2(sol, l1, l2) print "Chaotique par phenomène de resonance" print PremierRetournement(sol, N, times) AnimatonTrajMaillon(sol,l1, l2, N,times) def Maillon2(): "Fonction resolvant le problème du pendule double et l'affichant, etat non chaotique" g = 9.8 l1 = 10. l2 = 10. m1 = 1. m2 = 1. N = 300 times = 40. theta1 = np.pi/2. theta2 = np.pi/3. w1 = 0. w2 = 0. sol = SolveMaillon2(theta1, theta2, w1, w2, g, l1, l2, m1, m2, N, times, p1.step_RK4) PlotMaillon2(sol, N, times) PlotTrajMaillon2(sol, l1, l2) print "Non chaotique" print PremierRetournement(sol, N, times) def PremierRetournement(sol, N, times): "Fonction calculant le temps de premier retournement (en unité de temps)" i = 0 tps = 0. h = times/N sol_theta1 = map(lambda t : t[0], sol) sol_theta2 = map(lambda t : t[2], sol) for i in range(0, len(sol_theta2)): if(abs(sol_theta2[i]) <= np.pi): tps = tps + h else: return tps return "Pas de retournement" def Maillon2InitCdt(): "Fonction testant pour plusieurs theta2 initiaux proche le comportement du pendule" g = 9.8 l1 = 10. l2 = 10. m1 = 1. m2 = 1. N = 300 times = 40. theta1 = np.pi/2. theta2 = [np.pi/3.7,np.pi/3.4,np.pi/3.,np.pi/2.7,np.pi/2.5,np.pi/2.3,np.pi/2.,np.pi/1.8,np.pi/1.6] w1 = 0. w2 = 0. for i in range(0,len(theta2)): sol = SolveMaillon2(theta1, theta2[i], w1, w2, g, l1, l2, m1, m2, N, times, p1.step_RK4) print "Pendule double mailon theta2=",theta2[i] print "Premier retournement :", PremierRetournement(sol, N, times) AnimatonTrajMaillon(sol,l1, l2, N,times) if __name__ == "__main__": Maillon1() FrecTraceMaillon1() Maillon2() Maillon2Chaos() Maillon2InitCdt()
[ [ 1, 0, 0.0065, 0.0032, 0, 0.66, 0, 954, 0, 1, 0, 0, 954, 0, 0 ], [ 1, 0, 0.0097, 0.0032, 0, 0.66, 0.0556, 596, 0, 1, 0, 0, 596, 0, 0 ], [ 1, 0, 0.0129, 0.0032, 0, ...
[ "import numpy as np", "import matplotlib.pyplot as mp", "from matplotlib.animation import ArtistAnimation", "import partie1_methodes as p1", "def SolveMaillon1(theta, w, g, l, N, times, meth):\n\t\"Fonction resolvant le problème du pendule simple\"\n\th = times/N\n\teq = [(0.,[theta, w]),lambda X,t:np.array...
import numpy as np import matplotlib.pyplot as mp import partie1_methodes as p1 ### Test global ### def test_meth(): "verifie l'exactitude de meth_epsilon (et donc de meth_n_step) dans plusieurs cas" print "Tests de correction des methodes de resolution...\n" # y = e^x print "Equation : (y\'=y, y(0)=1) -> Solution : y = e^x" eq = [[0.,1.], lambda y,t: y] tf = 3. epsilon = 0.001 erreur = 0.1 Y = p1.meth_epsilon(eq,tf,epsilon,p1.step_euler) X = np.arange(0, tf, tf/len(Y)) Yref = np.exp(X) assert((abs(Y - Yref) < erreur).all) print " Euler : ok" Y = p1.meth_epsilon(eq,tf,epsilon,p1.step_ptmilieu) X = np.arange(0, tf, tf/len(Y)) Yref = np.exp(X) assert((abs(Y - Yref) < erreur).all) print " Point milieu : ok" Y = p1.meth_epsilon(eq,tf,epsilon,p1.step_heun) X = np.arange(0, tf, tf/len(Y)) Yref = np.exp(X) assert((abs(Y - Yref) < erreur).all) print " Heun : ok" Y = p1.meth_epsilon(eq,tf,epsilon,p1.step_RK4) X = np.arange(0, tf, tf/len(Y)) Yref = np.exp(X) assert((abs(Y - Yref) < erreur).all) print " RK4 : ok \n" # y = e^arctan(x) print "Equation : (y\'(t)=1/(1+t^2), y(0)=1) -> Solution : y = e^arctan(x)" eq = [[0.,1.], lambda y,t: y/(1+t**2)] tf = 3. epsilon = 0.001 erreur = 0.1 Y = p1.meth_epsilon(eq,tf,epsilon,p1.step_euler) X = np.arange(0, tf, tf/len(Y)) Yref = np.exp(X) assert((abs(Y - Yref) < erreur).all) print " Euler : ok" Y = p1.meth_epsilon(eq,tf,epsilon,p1.step_ptmilieu) X = np.arange(0, tf, tf/len(Y)) Yref = np.exp(X) assert((abs(Y - Yref) < erreur).all) print " Point milieu : ok" Y = p1.meth_epsilon(eq,tf,epsilon,p1.step_heun) X = np.arange(0, tf, tf/len(Y)) Yref = np.exp(X) assert((abs(Y - Yref) < erreur).all) print " Heun : ok" Y = p1.meth_epsilon(eq,tf,epsilon,p1.step_RK4) X = np.arange(0, tf, tf/len(Y)) Yref = np.exp(X) assert((abs(Y - Yref) < erreur).all) print " RK4 : ok\n" ### Applications graphiques des diverses methodes ### def plot_expo1(): "graphique des approximations de e^x obtenues avec un pas de 1" Yg = [[0.,1.], lambda y,t: y] mp.xlim(0,3) mp.ylim(1,5) x = np.arange(0, 5, 1) mp.plot(x,np.exp(x),label='y=e^x') mp.plot(x,p1.meth_n_step(Yg, 4, 1, p1.step_euler), label='Euler') mp.plot(x,p1.meth_n_step(Yg, 4, 1, p1.step_ptmilieu), label='Pt milieu') mp.plot(x,p1.meth_n_step(Yg, 4, 1, p1.step_heun), label='Heun') mp.plot(x,p1.meth_n_step(Yg, 4, 1, p1.step_RK4), label='RK4') mp.title('Resolution de (y\'=y, y(0)=1) avec h=1') mp.legend() mp.show() def plot_expo2(): "graphique des approximations de e^x obtenues avec un pas de 0.1" Yg = [[0.,1.], lambda y,t: y] mp.xlim(0,5) mp.ylim(1,30) x = np.arange(0, 10, 0.1) mp.plot(x,np.exp(x),label='y=e^x') mp.plot(x,p1.meth_n_step(Yg, 99, 0.1, p1.step_euler), label='Euler') mp.plot(x,p1.meth_n_step(Yg, 99, 0.1, p1.step_ptmilieu), label='Pt milieu') mp.plot(x,p1.meth_n_step(Yg, 99, 0.1, p1.step_heun), label='Heun') mp.plot(x,p1.meth_n_step(Yg, 99, 0.1, p1.step_RK4), label='RK4') mp.title('Resolution de (y\'=y, y(0)=1) avec h=0.1') mp.legend() mp.show() def plot_arctan_expo(): "graphique des approximations de e^arctan(x) obtenues avec un pas de 1" xmax = 10 h=1 N=xmax - 1 eq = [[0.,1.], lambda y,t: y/(1+t**2)] mp.xlim(0,xmax-1) mp.ylim(1,6.2) x = np.arange(0, xmax, h) mp.plot(x,np.exp(np.arctan(x)),label='y=e^arctan(x)') mp.plot(x,p1.meth_n_step(eq, N, h, p1.step_euler), label='Euler') mp.plot(x,p1.meth_n_step(eq, N, h, p1.step_ptmilieu), label='Pt milieu') mp.plot(x,p1.meth_n_step(eq, N, h, p1.step_heun), label='Heun') mp.plot(x,p1.meth_n_step(eq, N, h, p1.step_RK4), label='RK4') mp.title('Resolution de (y\'(t)=1/(1+t^2), y(0)=1) avec h=1') mp.legend() mp.show() def plot_equation_cercle1(): "Graphique approximations de cercle obtenues pour Euler avec differents pas" t0 = 0. y0 = [1., 0.] eq = [(t0,y0),lambda X,t:np.array([-X[1],X[0]])] times = 2*np.pi N = 5 h = times/N res = p1.meth_n_step(eq,N, h,p1.step_euler) tabres0 = map(lambda t : t[0], res) tabres1 = map(lambda t : t[1], res) mp.plot(tabres1, tabres0, linewidth=1.0, label='N=5') N = 10 h = times/N res = p1.meth_n_step(eq,N, h,p1.step_euler) tabres0 = map(lambda t : t[0], res) tabres1 = map(lambda t : t[1], res) mp.plot(tabres1, tabres0, linewidth=1.0, label='N=10') N = 20 h = times/N res = p1.meth_n_step(eq,N, h,p1.step_euler) tabres0 = map(lambda t : t[0], res) tabres1 = map(lambda t : t[1], res) mp.plot(tabres1, tabres0, linewidth=1.0, label='N=20') N = 100 h = times/N res = p1.meth_n_step(eq,N, h,p1.step_RK4) tabres0 = map(lambda t : t[0], res) tabres1 = map(lambda t : t[1], res) mp.plot(tabres1, tabres0, linewidth=1.0, label='reference') mp.title('Approximation du cercle avec Euler (h=2pi/N)') mp.legend() mp.show() def plot_equation_cercle2(): "Graphique des approximations de cercle obtenues pour le Pt milieu, Heun et RK4" N = 10 times = 2*np.pi h = times/N t0 = 0. y0 = [1., 0.] eq = [(t0,y0),lambda X,t:np.array([-X[1],X[0]])] #Euler res = p1.meth_n_step(eq,N, h,p1.step_euler) tabres0 = map(lambda t : t[0], res) tabres1 = map(lambda t : t[1], res) mp.plot(tabres1, tabres0, linewidth=1.0, label='Euler') #Point milieu res = p1.meth_n_step(eq,N, h,p1.step_ptmilieu) tabres0 = map(lambda t : t[0], res) tabres1 = map(lambda t : t[1], res) mp.plot(tabres1, tabres0, linewidth=1.0, label='Pt milieu') #Heun res = p1.meth_n_step(eq,N, h,p1.step_heun) tabres0 = map(lambda t : t[0], res) tabres1 = map(lambda t : t[1], res) mp.plot(tabres1, tabres0, linewidth=1.0, label='Heun') #RK4 res = p1.meth_n_step(eq,N, h,p1.step_RK4) tabres0 = map(lambda t : t[0], res) tabres1 = map(lambda t : t[1], res) mp.plot(tabres1, tabres0, linewidth=1.0, label='RK4') mp.title('Equation de cercle (N=10,h=2*pi/N)') mp.legend() mp.show() def plot_expo_meth_epsilon(): Yg = [[0.,1.], lambda y,t: y] tf = 3. mp.xlim(0,2) mp.ylim(1,4) x = np.arange(0, tf, 0.01) mp.plot(x,np.exp(x),label='y=e^x') epsilon = 2 y = p1.meth_epsilon(Yg,tf,epsilon,p1.step_euler) x = np.arange(0, tf, tf/len(y)) mp.plot(x,y, label='eps=2') epsilon = 1 y = p1.meth_epsilon(Yg,tf,epsilon,p1.step_euler) x = np.arange(0, tf, tf/len(y)) mp.plot(x,y, label='eps=1') epsilon = 0.1 y = p1.meth_epsilon(Yg,tf,epsilon,p1.step_euler) x = np.arange(0, tf, tf/len(y)) mp.plot(x,y, label='eps=0.1') mp.title('Resolution de (y\'=y, y(0)=1) avec epsilon variable') mp.legend() mp.show() def plot_champs_vecteurs(): eq = [[-2,np.exp(-4)],lambda t,y: -2*t*y] p1.champs_vecteurs(eq) eq = [[0,1],lambda t,y: y] p1.champs_vecteurs(eq,0,4) if __name__ == "__main__": test_meth() plot_expo1() plot_expo2() plot_arctan_expo() plot_equation_cercle1() plot_equation_cercle2() plot_champs_vecteurs()
[ [ 1, 0, 0.0041, 0.0041, 0, 0.66, 0, 954, 0, 1, 0, 0, 954, 0, 0 ], [ 1, 0, 0.0082, 0.0041, 0, 0.66, 0.0909, 596, 0, 1, 0, 0, 596, 0, 0 ], [ 1, 0, 0.0123, 0.0041, 0, ...
[ "import numpy as np", "import matplotlib.pyplot as mp", "import partie1_methodes as p1", "def test_meth():\n\t\"verifie l'exactitude de meth_epsilon (et donc de meth_n_step) dans plusieurs cas\"\n\tprint(\"Tests de correction des methodes de resolution...\\n\")\n\t\n\t# y = e^x\n\tprint(\"Equation : (y\\'=y, ...
import numpy as np import partie1_methodes as meth import matplotlib.pyplot as mp def Malthus(): nmax = 200 x = np.arange(0.,10.+10./nmax,10./nmax) mp.clf() birth = 3. death = 2. eq = [(0., [7e9]), lambda X,t:np.array([(birth-death)*X[0]])] res = meth.meth_n_step(eq, nmax, 10./nmax, meth.step_RK4) g1, = mp.plot(x,res,linewidth=1.0) mp.title("Malthus avec birth-death > 0") mp.savefig("../img/Malthus_birth_death_pos") mp.show() birth2 = 2. death2 = 3. eq2 = [(0., [7e9]), lambda X,t:np.array([(birth2-death2)*X[0]])] res2 = meth.meth_n_step(eq2, nmax, 10./nmax, meth.step_RK4) g2, = mp.plot(x,res2,linewidth=1.0) mp.title("Malthus avec birth-death < 0") mp.savefig("../img/Malthus_birth_death_neg") mp.show() def Verhulst(): nmax = 200 x = np.arange(0.,10.+10./nmax,10./nmax) mp.clf() gamma = 1. k = 20e9 eq = [(0., [7e9]), lambda X,t:np.array([gamma*X[0]*(1 - X[0]/k)])] res = meth.meth_n_step(eq, nmax, 10./nmax, meth.step_RK4) g1, = mp.plot(x,res,linewidth=1.0) gamma = 1. k = 10e9 eq2 = [(0., [7e9]), lambda X,t:np.array([gamma*X[0]*(1 - X[0]/k)])] res2 = meth.meth_n_step(eq2, nmax, 10./nmax, meth.step_RK4) g2, = mp.plot(x,res2,linewidth=1.0) mp.title("Methode Verhulst") mp.legend((g1,g2),("Verhulst gamma>0 / k = 20e9","Verhulst gamma > 0 / k =10e9")) mp.savefig("../img/Verhulst") mp.show() def LotkaVolterra(): nmax = 200 x = np.arange(0.,10.+10./nmax,10./nmax) mp.clf() a = 1. b = 0.2 c = 0.04 d = 0.5 eq = [(0.,[0.5,1.]), lambda X,t:np.array([X[0]*(a-b*X[1]),X[1]*(c*X[0]-d)])] res = meth.meth_n_step(eq, nmax, 50./nmax, meth.step_RK4) tabres0 = map(lambda t: t[0], res) tabres1 = map(lambda t: t[1], res) g1, = mp.plot(x,tabres0,linewidth=1.0) g2, = mp.plot(x,tabres1,linewidth=1.0) mp.legend((g1,g2),("Proies","Predateurs")) mp.title("Proies > Predateurs") mp.savefig("../img/ProiesSupPred") mp.show() mp.clf() a = 0.2 b = 0.4 c = 0.7 d = 0.5 nmax = 100 for i in range(20): eq = [(0.,[0.+0.1*i,0.+0.1*i]), lambda X,t:np.array([X[0]*(a-b*X[1]),X[1]*(c*X[0]-d)])] res = meth.meth_n_step(eq, nmax, 40./nmax, meth.step_RK4) tabres0 = map(lambda t: t[0], res) tabres1 = map(lambda t: t[1], res) g1, = mp.plot(tabres0,tabres1,linewidth=1.0) mp.axis([0.,3.,0.,3.5]) mp.title("Predateurs en fonction de proies") mp.savefig("../img/PredFoncProies") mp.show() mp.clf() a = 1. b = 1. c = 15. #tu peux essayer ici avec 20 d = 1. nmax = 200 eq = [(0.,[1.,1.]), lambda X,t:np.array([X[0]*(a-b*X[1]),X[1]*(c*X[0]-d)])] res = meth.meth_n_step(eq, nmax, 50./nmax, meth.step_RK4) tabres0 = map(lambda t: t[0], res) tabres1 = map(lambda t: t[1], res) g1, = mp.plot(x,tabres0,linewidth=1.0) g2, = mp.plot(x,tabres1,linewidth=1.0) mp.legend((g1,g2),("Proies","Predateurs")) mp.title("Proies < Predateurs") mp.savefig("../img/ProiesInfPred") mp.show() mp.clf() a = 0.2 b = 0.4 c = 0.7 d = 0.5 eq = [(0.,[d/c,a/b]), lambda X,t:np.array([X[0]*(a-b*X[1]),X[1]*(c*X[0]-d)])] res = meth.meth_n_step(eq, nmax, 50./nmax, meth.step_RK4) tabres0 = map(lambda t: t[0], res) tabres1 = map(lambda t: t[1], res) g1, = mp.plot(x,tabres0,linewidth=1.0) g2, = mp.plot(x,tabres1,linewidth=1.0) mp.axis([0.,1.,0.,1.]) mp.legend((g1,g2),("Proies","Predateurs")) mp.title("Solutions constantes") mp.savefig("../img/ConstSolLotka") mp.show()
[ [ 1, 0, 0.0076, 0.0076, 0, 0.66, 0, 954, 0, 1, 0, 0, 954, 0, 0 ], [ 1, 0, 0.0153, 0.0076, 0, 0.66, 0.2, 50, 0, 1, 0, 0, 50, 0, 0 ], [ 1, 0, 0.0229, 0.0076, 0, 0.66,...
[ "import numpy as np", "import partie1_methodes as meth", "import matplotlib.pyplot as mp", "def Malthus():\n \n nmax = 200\n x = np.arange(0.,10.+10./nmax,10./nmax)\n\n mp.clf()\n birth = 3.\n death = 2.", " nmax = 200", " x = np.arange(0.,10.+10./nmax,10./nmax)", " mp.clf()",...
import numpy as np import matplotlib.pyplot as mp import partie1 as p1 def equation_2_corps(mA): """Cree une fonction decrivant les equations pour 2 corps pour le probleme de cauchy Entree: mA reel masse du corps A Sortie: f fonction equation du mouvement""" def f(t,y): return [y[2],y[3],(y[0]*y[3]*y[3]-1.0*mA/(y[0]*y[0])), -2.0*y[2]*y[3]/y[0]] return f def meca_2_corps (r0,teta0,vr0,vteta0, t0, mA, N, pas): """Calcul les positions succesive du corps B avec la methode de runge kutta 4 Entree: r0 reel distance initiale entre le corps A et B teta0 reel angle initial du corps B en radian vr0 reel vitesse initiale selon er vteta0 reel vitesse initiale selon eteta t0 reel temps initial mA reel masse du corps A N entier nombre de pas pas reel taille du pas Sortie: x tableau contenant les positions succesive selon ex y tableau contenant les positions succesive selon ey t tableau contenant les temps""" condition_init = np.array([r0,teta0,vr0,vteta0]) #On calcule les positions succesives tab = p1.meth_n_step(condition_init, t0, N, pas, equation_2_corps(mA), p1.step_runge_kutta_4) n = len(tab) #On remplie le tableau des temps t = np.zeros(n) for i in range(0,n): t[i] = t0+i*pas #On decompose la liste calculee avant en deux tableaux en projetant sur le repere (ex,ey) x = np.zeros(n) y = np.zeros(n) for i in np.arange(0,n,1): x[i] = tab[i][0]*np.cos(tab[i][1]) y[i] = tab[i][0]*np.sin(tab[i][1]) return (x,y,t) def equation_3_corps(mA, mB): """Cree une fonction decrivant les equations du mouvement pour 3 corps pour le probleme de cauchy Entree: mA reel masse du corps A mB reel masse du coprs B Sortie: f fonction equation du mouvement""" def f(t,y): rcb2 = y[2]*y[2]+y[0]*y[0]-2.0*y[2]*y[0]*np.cos(y[1]-y[3]) return [y[4], y[5], y[6], y[7], -mA/(y[0]*y[0])+y[0]*y[5]*y[5]+mB*(y[2]*np.cos(y[1]-y[3])-y[0])/pow(rcb2,3./2.), (-2.*y[4]*y[5]-mB*y[2]*np.sin(y[1]-y[3])/pow(rcb2,3./2.))/y[0], 0, 0] return f def meca_3_corps (r0,teta0, b0, alpha0, vr0,vteta0, vb0, valpha0, t0, mA, mB, N, pas): """Calcul les positions succesive du corps C avec la methode de runge kutta 4 Entree: r0 reel distance initiale entre le corps A et C teta0 reel angle initial du corps C en radian b0 reel distance initiale entre le corps A et B alpha0 reel angle initial du corps B en radian vr0 reel vitesse initiale selon er du corps C vteta0 reel vitesse initiale selon eteta du corps C vb0 reel vitesse initiale selon er du corps B valpha0 reel vitesse initiale selon eteta du corps B t0 reel temps initial mA reel masse du corps A mB reel masse du corps B N entier nombre de pas pas reel taille du pas Sortie: xC tableau contenant les positions succesive du corps C selon ex yC tableau contenant les positions succesive du corps C selon ey xB tableau contenant les positions succesive du corps B selon ex yB tableau contenant les positions succesive du corps B selon ey t tableau contenant les temps""" condition_init = np.array([r0,teta0, b0, alpha0, vr0,vteta0, vb0, valpha0]) #On calcule les positions succesives tab = p1.meth_n_step(condition_init, t0, N, pas, equation_3_corps(mA,mB), p1.step_runge_kutta_4) n = len(tab) #On remplie le tableau des temps t = np.zeros(n) for i in range(0,n): t[i] = t0+i*pas xC = np.zeros(n) yC = np.zeros(n) xB = np.zeros(n) yB = np.zeros(n) #On decompose la liste calculee avant en quatre tableaux en projetant sur le repere (ex,ey) for i in np.arange(0,n,1): xC[i] = tab[i][0]*np.cos(tab[i][1]) yC[i] = tab[i][0]*np.sin(tab[i][1]) xB[i] = tab[i][2]*np.cos(tab[i][3]) yB[i] = tab[i][2]*np.sin(tab[i][3]) return (xC,yC,xB,yB,t) def meca_3_corps_B_fixe (r0,teta0, b0, alpha0, vr0,vteta0, vb0, valpha0, t0, mA, mB, N, pas): """Calcul les positions succesive du corps C avec la methode de runge kutta 4 en se placant dans le repere ou A et B sont fixe Entree: r0 reel distance initiale entre le corps A et C teta0 reel angle initial du corps C en radian b0 reel distance initiale entre le corps A et B alpha0 reel angle initial du corps B en radian vr0 reel vitesse initiale selon er du corps C vteta0 reel vitesse initiale selon eteta du corps C vb0 reel vitesse initiale selon er du corps B valpha0 reel vitesse initiale selon eteta du corps B t0 reel temps initial mA reel masse du corps A mB reel masse du corps B N entier nombre de pas pas reel taille du pas Sortie: xC tableau contenant les positions succesive du corps C selon ex yC tableau contenant les positions succesive du corps C selon ey xB tableau contenant les positions succesive du corps B selon ex yB tableau contenant les positions succesive du corps B selon ey t tableau contenant les temps""" condition_init = np.array([r0,teta0, b0, alpha0, vr0,vteta0, vb0, valpha0]) #On calcule les positions succesives tab = p1.meth_n_step(condition_init, t0, N, pas, equation_3_corps(mA,mB), p1.step_runge_kutta_4) n = len(tab) #On remplie le tableau des temps t = np.zeros(n) for i in range(0,n): t[i] = t0+i*pas xC = np.zeros(n) yC = np.zeros(n) xB = np.zeros(n) yB = np.zeros(n) #On decompose la liste calculee avant en quatre tableaux en projetant sur le repere (er,eteta) du corps B for i in np.arange(0,n,1): xC[i] = tab[i][0]*np.cos(tab[i][1]-tab[i][3]) yC[i] = tab[i][0]*np.sin(tab[i][1]-tab[i][3]) xB[i] = tab[i][2]*np.cos(tab[i][3]-tab[i][3]) yB[i] = tab[i][2]*np.sin(tab[i][3]-tab[i][3]) return (xC,yC,xB,yB,t)
[ [ 1, 0, 0.0061, 0.0061, 0, 0.66, 0, 954, 0, 1, 0, 0, 954, 0, 0 ], [ 1, 0, 0.0123, 0.0061, 0, 0.66, 0.1429, 596, 0, 1, 0, 0, 596, 0, 0 ], [ 1, 0, 0.0184, 0.0061, 0, ...
[ "import numpy as np", "import matplotlib.pyplot as mp", "import partie1 as p1", "def equation_2_corps(mA):\n \"\"\"Cree une fonction decrivant les equations pour 2 corps pour le probleme de cauchy\n Entree: mA reel masse du corps A\n Sortie: f fonction equation du mouvement\"\"\"\n def f(t,y):\...
import numpy as np import matplotlib.pyplot as mp import partie1 as p1 ####################################################### ## Modele de population malthusiens (Malthus) ## ####################################################### def EquationMalthus (b,d): def f(t,y): return [b*y[0]-d*y[0]] return f def ResolutionMalthus(y0, t0, b, d, N, pas, meth): y = p1.meth_n_step(y0, t0, N, pas, EquationMalthus(b,d), meth) n = len(y) t = np.zeros(n) for i in range(0,n): t[i] = t0+i*pas return (t,y) ########################################################## ## Modele de polulation auto limitant (Verhulst) ## ########################################################## def EquationVerhulst (a,c): def f(t,y): return [a*y[0]*(1-y[0]/c)] return f def ResolutionVerhulst(y0, t0, a, c, N, pas, meth): y = p1.meth_n_step(y0, t0, N, pas, EquationVerhulst(a,c), meth) n = len(y) t = np.zeros(n) for i in range(0,n): t[i] = t0+i*pas return (t,y) ############################################## ## Modele de Lotka Volterra ## ############################################## def EquationLotka (a, b, c, d): def f(t,y): return [y[0]*(a-b*y[1]), y[1]*(c*y[0]-d)] return f def ResolutionLotka(y0, t0, a, b, c, d, N, pas, meth): tab = p1.meth_n_step(y0, t0, N, pas, EquationLotka(a,b,c,d), meth) n = len(tab) t = np.zeros(n) for i in range(0,n): t[i] = t0+i*pas y_N=np.zeros(n) y_P=np.zeros(n) for i in np.arange(n): y_N[i] = tab[i][0] y_P[i] = tab[i][1] return (y_N, y_P, t) ############################################## ## Calcul Periode ## ############################################## def CalculPeriode(t,y,equa): n = len(y) courant = equa(t,y[0]) nb_changement = 0 for i in range(1,n): precedent = courant courant = equa(t,y[i]) if (courant[0]*precedent[0] <= 0): nb_changement += 1 if (nb_changement == 1): debut = i else: if (nb_changement == 3): return (t[i]-t[debut]) return -1
[ [ 1, 0, 0.0115, 0.0115, 0, 0.66, 0, 954, 0, 1, 0, 0, 954, 0, 0 ], [ 1, 0, 0.023, 0.0115, 0, 0.66, 0.1111, 596, 0, 1, 0, 0, 596, 0, 0 ], [ 1, 0, 0.0345, 0.0115, 0, 0...
[ "import numpy as np", "import matplotlib.pyplot as mp", "import partie1 as p1", "def EquationMalthus (b,d):\n def f(t,y):\n return [b*y[0]-d*y[0]]\n return f", " def f(t,y):\n return [b*y[0]-d*y[0]]", " return [b*y[0]-d*y[0]]", " return f", "def ResolutionMalthus(y0, t...
import numpy as np import matplotlib.pyplot as mp import partie5 as p5 import math def Test_Video2Corps(r0,teta0,vr0,vteta0, t0, m, N, pas, nom): res = p5.meca_2_corps(r0,teta0,vr0,vteta0,t0,m,N,pas) minx = min(res[0]) maxx = max(res[0]) miny = min(res[1]) maxy = max(res[1]) for i in np.arange(len(res[0])): mp.axis([minx-10,maxx+10,miny-10,maxy+10]) x = np.array([0]) y = np.array([0]) mp.plot(x,y,'o',color ='red') mp.plot(res[0][i], res[1][i],'o',color = 'green') mp.savefig('video/'+nom+'%d'%i) mp.clf() def Test_Video3Corps(r0,teta0, b0, alpha0, vr0,vteta0, vb0, valpha0, t0, mA, mB, N, pas, nom): res = p5.meca_3_corps(r0,teta0, b0, alpha0, vr0,vteta0, vb0, valpha0, t0, mA, mB, N, pas) min1x = min(res[0]) max1x = max(res[0]) min1y = min(res[1]) max1y = max(res[1]) min2x = min(res[2]) max2x = max(res[2]) min2y = min(res[3]) max2y = max(res[3]) minx = min(min1x,min2x) maxx = max(max1x,max2x) miny = min(min1y,min2y) maxy = max(max1y,max2y) for i in np.arange(len(res[0])): mp.axis([minx-5,maxx+5,miny-5,maxy+5]) x = np.array([0]) y = np.array([0]) mp.plot(res[0][i], res[1][i],'o',color = 'red') mp.plot(x,y,'o',color = 'green') mp.plot(res[2][i],res[3][i],'o',color = 'blue') mp.savefig('video/'+nom+'%d'%i) mp.clf() def Test_Video3Corps_B_fixe(r0,teta0, b0, alpha0, vr0,vteta0, vb0, valpha0, t0, mA, mB, N, pas, nom): res = p5.meca_3_corps_B_fixe(r0,teta0, b0, alpha0, vr0,vteta0, vb0, valpha0, t0, mA, mB, N, pas) min1x = min(res[0]) max1x = max(res[0]) min1y = min(res[1]) max1y = max(res[1]) min2x = min(res[2]) max2x = max(res[2]) min2y = min(res[3]) max2y = max(res[3]) minx = min(min1x,min2x) maxx = max(max1x,max2x) miny = min(min1y,min2y) maxy = max(max1y,max2y) for i in np.arange(len(res[0])): mp.axis([minx-5,maxx+5,miny-5,maxy+5]) x = np.array([0]) y = np.array([0]) mp.plot(res[0][i], res[1][i],'o',color = 'red') mp.plot(x,y,'o',color = 'green') mp.plot(res[2][i],res[3][i],'o',color = 'blue') mp.savefig('video/'+nom+'%d'%i) mp.clf() #Test_Video3Corps(42.0, 0.0, 40.0, 0.0, 0.0, 0.1,0.0, 0.1, 0.0, 640, 60, 1000, 0.1, "img") Test_Video2Corps(40.0,0.0,0.0,0.06,0.0,5000.0, 800, 0.01,"m2c") Test_Video3Corps(30.0, math.pi/4.0, 30.0, 0.0, 0.0, 0.1,0.0, 0.1, 0.0, 800, 100, 1100, 0.1, "m3c") Test_Video3Corps_B_fixe(30.0, math.pi/4.0, 30.0, 0.0, 0.0, 0.1,0.0, 0.1, 0.0, 800, 100, 1100, 0.1, "m3c_fixe")
[ [ 1, 0, 0.0132, 0.0132, 0, 0.66, 0, 954, 0, 1, 0, 0, 954, 0, 0 ], [ 1, 0, 0.0263, 0.0132, 0, 0.66, 0.1111, 596, 0, 1, 0, 0, 596, 0, 0 ], [ 1, 0, 0.0395, 0.0132, 0, ...
[ "import numpy as np", "import matplotlib.pyplot as mp", "import partie5 as p5", "import math", "def Test_Video2Corps(r0,teta0,vr0,vteta0, t0, m, N, pas, nom):\n res = p5.meca_2_corps(r0,teta0,vr0,vteta0,t0,m,N,pas)\n minx = min(res[0])\n maxx = max(res[0])\n miny = min(res[1])\n maxy = max(re...
import numpy as np import matplotlib.pyplot as mp ################################################ # Calcul d'un pas selon 4 methodes differentes # ################################################ def step_euler (y, t, h, f): """ fonction calculant un seul pas par la methode d'Euler """ n = len(y) fty = f(t,y) res = [] for i in np.arange(n): res.append(y[i]+h*fty[i]) return res def step_milieu (y, t, h, f): """ fonction calculant un seul pas par la methode du point du milieu """ n = len(y) fty = f(t,y) res = [] for i in np.arange(n): res.append(y[i] + h/2.*fty[i]) p = f(t + h/2., y) for i in np.arange(n): res[i] = res[i] + h/2.*p[i] return res def step_heun (y, t, h, f): """ fonction calculant un seul pas par la methode de Heun """ n = len(y) p1 = f(t,y) y1 = [] res = [] for i in np.arange(n): y1.append(y[i] + h*p1[i]) p2 = f(t + h, y1) for i in np.arange(n): res.append(y[i] + (1./2.)*h*(p1[i]+p2[i])) return res def step_runge_kutta_4 (y, t, h, f): """ fonction calculant un seul pas par la methode de Runge Kutta """ n = len(y) p1 = f(t,y) y1 = [] res = [] for i in np.arange(n): y1.append(y[i]+(1./2.)*h*p1[i]) p2 = f(t+(1./2.)*h,y1) y2 = [] for i in np.arange(n): y2.append(y[i]+(1./2.)*h*p2[i]) p3 = f(t+(1./2.)*h,y2) y3 = [] for i in np.arange(n): y3.append(y[i]+h*p3[i]) p4 = f(t+h,y3) for i in np.arange(n): res.append(y[i]+(1./6.)*h*(p1[i]+2.*(p2[i]+p3[i])+p4[i])) return res ####################################### # Fonction auxiliaire calculant N pas # ####################################### # elle retourne une liste de N+1 elements def meth_n_step (y0, t0, N, h, f, meth): """ fonction retournant la liste de pas (y0, y1, etc., yN) calcules avec la methode choisie en parametre """ y = [] y.append(y0) t=t0 for i in np.arange(0,int(N)): y.append(meth(y[i],t,h,f)) t=t+h return y ############################################################# # Fonction calculant la solution avec une precision epsilon # ############################################################# # la precision epsilon doit etre superieure ou egale a la norme absolue de la difference des vecteurs (yN - y2N) # elle retourne la liste de pas y2N obtenue au bout de la kieme iteration def norme_absolue (y1, y2): """ fonction auxiliaire calculant la norme absolue de la difference de deux vecteurs y1 et y2 """ diff = (y1 - y2) res = (np.abs(diff)).max() return res def meth_epsilon (y0, t0, tf, eps, f, meth): """ fonction calculant une solution approchee avec un parametre epsilon """ h1 = np.abs((tf - t0)/2) h2 = h1/2 yN = np.array([[meth_n_step (y0, t0, N, h1, f, meth)]]) y2N = np.array([[meth_n_step (y0, t0, N, h2, f, meth)]]) normeabs = norme_absolue (yN, y2N) while (normeabs > eps): h1 = h2 h2 = h1/2 yN = np.array([[meth_n_step (y0, t0, N, h1, f, meth)]]) y2N = np.array([[meth_n_step (y0, t0, N, h2, f, meth)]]) normeabs = norme_absolue (yN, y2N) res = list(np.array(y2n).reshape(-1,)) return res ########################################################### # Dessin des tangentes # ########################################################### def plot_tangentes(xmin,xmax,ymin,ymax,pas,f,nom_fichier): """ fonction dessinant le champ des tangentes de l'equation differentielle en dimension 2 """ mp.clf() x = [] y = [] dx = [] dy = [] for i in np.arange(xmin,xmax,pas): for j in np.arange(ymin,ymax,pas): x.append(i) y.append(j) fy = f(0,[i,j]) dx.append(fy[0]) dy.append(fy[1]) mp.quiver(x,y,dx,dy) mp.savefig (nom_fichier) mp.clf()
[ [ 1, 0, 0.0077, 0.0077, 0, 0.66, 0, 954, 0, 1, 0, 0, 954, 0, 0 ], [ 1, 0, 0.0154, 0.0077, 0, 0.66, 0.1111, 596, 0, 1, 0, 0, 596, 0, 0 ], [ 2, 0, 0.0885, 0.0615, 0, ...
[ "import numpy as np", "import matplotlib.pyplot as mp", "def step_euler (y, t, h, f):\n \"\"\" fonction calculant un seul pas par la methode d'Euler \"\"\"\n n = len(y)\n fty = f(t,y)\n res = []\n for i in np.arange(n):\n res.append(y[i]+h*fty[i])\n return res", " \"\"\" fonction c...
from os import listdir, system from os.path import isfile, join import re import sys import math def digrafo(nodos, aristas, salida): return '2 '+ str(nodos) + ' ' + str(aristas) + ' ' + '1' + ' ' + '1' + ' '\ + salida +'_'+ str(nodos).zfill(5) +'_'+ str(aristas) + '.graph' + ' 0' def dag(nodos, aristas, salida): return '4 '+ str(nodos) + ' ' + str(aristas) + ' ' + '1' + ' ' \ + salida +'_'+ str(nodos).zfill(5) +'_'+ str(aristas) + '.graph' + ' ' \ + 'ts.txt 0' if __name__ == '__main__': mypath = '.' #1000 nodos, 1000 aristas, cambia c cantidad componetnes conexas output = sys.argv[1] tipo = sys.argv[2] n = int(sys.argv[3]) m = int(sys.argv[4] ) for t in range(1, n): #generamos entrada para el algoritmo input = open('input_'+output , 'w+'); if(tipo == 'dag'): input.write(dag(t, m, output)) if(tipo == 'dig'): input.write(digrafo(t, m, output)) input.close() #generamos un grafo con la entrada anterior system("generador.exe " + ' < input_'+output) system("pruebas.py " + output)
[ [ 1, 0, 0.027, 0.027, 0, 0.66, 0, 688, 0, 2, 0, 0, 688, 0, 0 ], [ 1, 0, 0.0541, 0.027, 0, 0.66, 0.1429, 79, 0, 2, 0, 0, 79, 0, 0 ], [ 1, 0, 0.0811, 0.027, 0, 0.66, ...
[ "from os import listdir, system", "from os.path import isfile, join", "import re", "import sys", "import math", "def digrafo(nodos, aristas, salida):\n\treturn '2 '+ str(nodos) + ' ' + str(aristas) + ' ' + '1' + ' ' + '1' + ' '\\\n\t+ salida +'_'+ str(nodos).zfill(5) +'_'+ str(aristas) + '.graph' + ' 0'"...
from os import listdir, system from os.path import isfile, join import sys from StringIO import StringIO import re if __name__ == '__main__': mypath = '.' output = sys.argv[1] files = [ f for f in listdir(mypath) if isfile(join(mypath,f)) and re.match(output+'.*\.graph$', f) ] mo = re.match('([0-9 a-z A-Z ]+)', files[0]) outputFile=open(output, 'w+') for arg in files : print arg inFile = open(arg) for line in inFile.readlines(): mo = re.match('^\s*?([0-9]+)\s*?([0-9]+)', line) string = mo.group(1) + ' ' + mo.group(2) outputFile.write(string+'\n') outputFile.write('#') outputFile.close()
[ [ 1, 0, 0.037, 0.037, 0, 0.66, 0, 688, 0, 2, 0, 0, 688, 0, 0 ], [ 1, 0, 0.0741, 0.037, 0, 0.66, 0.2, 79, 0, 2, 0, 0, 79, 0, 0 ], [ 1, 0, 0.1111, 0.037, 0, 0.66, ...
[ "from os import listdir, system", "from os.path import isfile, join", "import sys", "from StringIO import StringIO", "import re", "if __name__ == '__main__':\n\tmypath = '.'\n\toutput = sys.argv[1]\n\tfiles = [ f for f in listdir(mypath) if isfile(join(mypath,f)) and re.match(output+'.*\\.graph$', f) ]\n...
from os import listdir, system from os.path import isfile, join import re import sys import math def digrafo(nodos, aristas, salida): return '2 '+ str(nodos) + ' ' + str(aristas) + ' ' + '1' + ' ' + '1' + ' '\ + salida +'_'+ str(nodos) +'_'+ str(aristas).zfill(5) + '.graph' + ' 0' def dag(nodos, aristas, salida): return '4 '+ str(nodos) + ' ' + str(aristas) + ' ' + '1' + ' ' \ + salida +'_'+ str(nodos) +'_'+ str(aristas).zfill(5) + '.graph' + ' ' \ + 'ts.txt 0' if __name__ == '__main__': mypath = '.' #1000 nodos, 1000 aristas, cambia c cantidad componetnes conexas output = sys.argv[1] tipo = sys.argv[2] n = int(sys.argv[3]) m = int(sys.argv[4] ) for m in range(1, m): #generamos entrada para el algoritmo input = open('input_'+output , 'w+'); if(tipo == 'dag'): input.write(dag(n, m, output)) if(tipo == 'dig'): input.write(digrafo(n, m, output)) input.close() #generamos un grafo con la entrada anterior system("generador.exe " + ' < input_'+output) system("pruebas.py " + output)
[ [ 1, 0, 0.027, 0.027, 0, 0.66, 0, 688, 0, 2, 0, 0, 688, 0, 0 ], [ 1, 0, 0.0541, 0.027, 0, 0.66, 0.1429, 79, 0, 2, 0, 0, 79, 0, 0 ], [ 1, 0, 0.0811, 0.027, 0, 0.66, ...
[ "from os import listdir, system", "from os.path import isfile, join", "import re", "import sys", "import math", "def digrafo(nodos, aristas, salida):\n\treturn '2 '+ str(nodos) + ' ' + str(aristas) + ' ' + '1' + ' ' + '1' + ' '\\\n\t+ salida +'_'+ str(nodos) +'_'+ str(aristas).zfill(5) + '.graph' + ' 0'"...
import numpy as np import newton as nw import matplotlib.pyplot as plt #------------------------------------------------------------------------# # EQUILIBRE ELECTROSTATIQUE # #------------------------------------------------------------------------# def term_energy_E(n,k): "Calcule les différents termes de la fonction à étudier" def f(X): s = 0 for i in np.arange(0,n): if(i != k): s = s + (1/(X[k]-X[i])) return s + (1/(X[k]+1)) + (1/(X[k]-1)) return f def fct_energy_E(n): "Retourne le tableau de fonction à étudier pour n charges" F=[] for i in np.arange(0,n): F = F + [term_energy_E(n,i)] return F def f1(f,i): "Fonction intermédiaire du calcule de la matrice de Jacobi" return lambda X: (-1/((X[i]+1)**2))-(1/((X[i]-1)**2) + f(X)) def f2(f,i,j): "Fonction intermédiaire du calcule de la matrice de Jacobi" return lambda X: 1/((X[i]-X[j])**2) def jacob_E(n): "Retourne la matrice de jacobi de la fonction energie" J = [] for i in np.arange(0,n): J2 = [] for j in np.arange(0,n): if(i == j): def f(X): s = 0. for k in np.arange(0,n): if(i != k): s = s - (1/(X[i]-X[k]))**2 return s J2 = J2 + [f1(f,i)] else: J2 = J2 + [f2(f,i,j)] J = J + [J2] return J #------------------------------------------------------------------------# # APPLICATION AUX POLYNOMES DE LEGENDRE # #------------------------------------------------------------------------# def P1(x): "Dérivée du second polynome de Legendre" return 3*x def P2(x): "Dérivée du troisième polynome de Legendre" return 0.5*(15.*x*x-3) def P3(x): "Dérivée du quatrième polynome de Legendre" return 0.125*(140.*x*x*x-60.*x) def P4(x): "Dérivée du cinquième polynome de Legendre" return 0.125*(315.*x**4-210.*x**2+15.) def test_legendre(): "Test la méthode de Newton-Raphson pour la fonctions f avec backtracking" x = np.arange(-1., 1., 0.01) plt.clf() g = plt.plot(x, P1(x), 'm', linewidth=1.0) h = plt.plot(x, P2(x), 'g', linewidth=1.0) i = plt.plot(x, P3(x), 'r', linewidth=1.0) j = plt.plot(x, P4(x), 'b', linewidth=1.0) U = np.asmatrix([-0.9]).T Res = nw.newton_raphson_backtrack(fct_energy_E(1), jacob_E(1), U, 10, nw.epsilon) plt.plot(Res[0],0,'o') U = np.asmatrix([-0.9,0.9]).T Res = nw.newton_raphson_backtrack(fct_energy_E(2), jacob_E(2), U, 10, nw.epsilon) plt.plot(Res[0],0,'o') plt.plot(Res[1],0,'o') U = np.asmatrix([-0.9,0.,0.9]).T Res = nw.newton_raphson_backtrack(fct_energy_E(3), jacob_E(3), U, 10, nw.epsilon) plt.plot(Res[0],0,'o') plt.plot(Res[1],0,'o') plt.plot(Res[2],0,'o') U = np.asmatrix([-0.8,-0.1,0.1,0.8]).T Res = nw.newton_raphson_backtrack(fct_energy_E(4), jacob_E(4), U, 10, nw.epsilon) plt.plot(Res[0],0,'o') plt.plot(Res[1],0,'o') plt.plot(Res[2],0,'o') plt.plot(Res[3],0,'o') plt.axis([-1,1,-5,5]) plt.legend((g,h,i,j),("n = 1","n = 2","n = 3","n = 4")) test_legendre() #------------------------------------------------------------------------# # MAXIMUM OU MINIMUM # #------------------------------------------------------------------------# def energy(x): "Retourne l'énergie totale du système" n = x.shape[1] Res = 0. for i in np.arange(0,n): Res = Res + np.log(abs(x[i]+1)) + np.log(abs(x[i]-1)) for j in np.arange(0,n): if(i != j): Res = Res + np.log(abs(x[i]-x[j])) return Res def min_max(): "Trac l'évolution de l'énergie du système au cours de la méthode de Newton Raphson" plt.clf() x = np.arange(0., 10., 1) y1 = np.arange(0.0, 10, 1) y2 = np.arange(0.0, 10, 1) y3 = np.arange(0.0, 10, 1) U = np.asmatrix([-0.9]).T for i in np.arange(0,10): Res = nw.newton_raphson_backtrack(fct_energy_E(1), jacob_E(1), U, i, nw.epsilon) y1[i] = energy(Res) U = np.asmatrix([-0.9,0.9]).T for i in np.arange(0,10): Res = nw.newton_raphson_backtrack(fct_energy_E(2), jacob_E(2), U, i, nw.epsilon) y2[i] = energy(Res) U = np.asmatrix([-0.9,0.,0.9]).T for i in np.arange(0,10): Res = nw.newton_raphson_backtrack(fct_energy_E(3), jacob_E(3), U, i, nw.epsilon) y3[i] = energy(Res) g = plt.plot(x, y1, linewidth=1.0) h = plt.plot(x, y2, linewidth=1.0) j = plt.plot(x, y3, linewidth=1.0) plt.xlabel('Nombre iterations de la suite de Newton-Raphson') plt.ylabel('Energie du systeme') plt.legend((g,h,j),("n = 1","n = 2","n = 3")) min_max()
[ [ 1, 0, 0.0063, 0.0063, 0, 0.66, 0, 954, 0, 1, 0, 0, 954, 0, 0 ], [ 1, 0, 0.0126, 0.0063, 0, 0.66, 0.0625, 270, 0, 1, 0, 0, 270, 0, 0 ], [ 1, 0, 0.0189, 0.0063, 0, ...
[ "import numpy as np", "import newton as nw", "import matplotlib.pyplot as plt", "def term_energy_E(n,k):\n \"Calcule les différents termes de la fonction à étudier\"\n def f(X): \n s = 0\n for i in np.arange(0,n):\n if(i != k):\n s = s + (1/(X[k]-X[i]))\n r...
# -*- coding:utf-8 -*- import numpy as np import matplotlib.pyplot as plt epsilon = 0.00000000000001 nmax = 1000 #------------------------------------------------------------------------# # METHODE DE NEWTON-RAPHSON # #------------------------------------------------------------------------# def newton_raphson(f, J, U0, N, epsilon): "Implementation de la methode de newton-raphson pour une fonction f" n = len(J[0]) #Dimension de l'espace de départ m = len(J) #Dimension de l'espace d'arrivée U = U0 #Premier terme de la suite V = np.zeros(U.shape[0]) for i in np.arange(0,N): f_U = f_X(f,U,n,m) V = np.linalg.lstsq(J_X(J,U,n,m),-f_U)[0] #On résoud l'équation f(U)+H(U)*V=0 U = U + V if (np.linalg.norm(f_X(f,U,n,m)) < epsilon): return U return U def newton_raphson_backtrack(f, J, U0, N, epsilon): "Implementation de la methode de newton-raphson avec backtracking pour une fonction f" n = len(J[0]) #Dimension de l'espace de départ m = len(J) #Dimension de l'espace d'arrivée U = U0 #Premier terme de la suite V = np.zeros(U.shape[0]) for i in np.arange(0,N): step = 1.0 f_U = f_X(f,U,n,m) norm_f = np.linalg.norm(f_U) V = np.linalg.lstsq(J_X(J,U,n,m),-f_U)[0] #On résoud l'équation f(U)+H(U)*V=0 while(np.linalg.norm(f_X(f,U + step*V,n,m)) > np.linalg.norm(f_U)): step = step * (2./3.) #On effectue le backtracking U = U + step*V if (np.linalg.norm(f_X(f,U,n,m)) < epsilon): return U return U def f_X(f,X,n,m): "Calcule les composantes de f(X)" Y = np.zeros([m,1]) for i in np.arange(0,m): Y[i] = f[i](X) return Y def J_X(J,X,n,m): "Calcule les composantes de la matrice de Jacobi" Y = np.zeros([m,n]) for i in np.arange(0,m): for j in np.arange(0,n): Y[i][j] = J[i][j](X) return Y #------------------------------------------------------------------------# # TEST DE LA METHODE DE NEWTON-RAPHSON # #------------------------------------------------------------------------# U = np.asmatrix([1, 2, 3]).T#Les vecteurs d'entre doivent etre des vecteurs colonnes f = [lambda x: x[1]*x[2]-4,lambda x: x[0]*x[2],lambda x: x[0]*x[1],lambda x: x[0]*x[1]*x[2]] g = [lambda x: x[0]*x[1]-3,lambda x: x[1]*x[2]-5, lambda x: x[0]*x[2] -8, lambda x: 0] J = [[lambda x: 0,lambda x: x[2],lambda x: x[1]],[lambda x: x[2],lambda x: 0,lambda x: x[0]],[lambda x: x[1],lambda x: x[0],lambda x: 0],[lambda x: x[1]*x[2],lambda x: x[0]*x[2],lambda x: x[0]*x[1]]] Jg = [[lambda x: x[1], lambda x: x[0], lambda x: 0], [lambda x: 0, lambda x: x[2], lambda x: x[1]], [lambda x: x[2], lambda x: 0, lambda x: x[1]], [lambda x: 0, lambda x: 0, lambda x: 0]] print "\n" print "------------------------------------------------------------------------" print " TEST DE LA METHODE DE NEWTON-RAPHSON " print "------------------------------------------------------------------------" print "\n" print "f(x,y,z) = (yz-4, xz, xy, xyz)" print "g(x,y,z) = (xy-3, yz-5, xz-8, 0)" print "\n" print "Resultat de Newton-Raphson f:" print newton_raphson(f, J, U, nmax, epsilon) print "\n" print "Image de ce vecteur par f:" print f_X(f,newton_raphson(f, J, U, nmax, epsilon),3,4) print "\n" U = np.asmatrix([1, 1, 1]).T print "Resultat de Newton-Raphson g:" print newton_raphson(g, Jg, U, nmax, epsilon) print "\n" print "Image de ce vecteur par g:" print f_X(g,newton_raphson(g, Jg, U, nmax, epsilon),3,4) def test_conv(): "Test la méthode de Newton-Raphson pour les fonctions f et g" x = np.arange(0.0, 6, 1) u = np.arange(0.0, 6, 1) v = np.arange(0.0, 6, 1) for i in np.arange(0,u.size): u[i] = np.linalg.norm(f_X(f,newton_raphson(f, J, U, i, epsilon),3,4)) for i in np.arange(0,v.size): v[i] = np.linalg.norm(f_X(g,newton_raphson(g, Jg, U, i, epsilon),3,4)) plt.clf() k = plt.plot(x, u, linewidth=1.0) h = plt.plot(x, v, linewidth=1.0) plt.xlabel('Nombre d\'iterations de la suite de Newton-Raphson') plt.ylabel('Norme de l\'image du resultat') plt.legend((k,h),("Fonction f","Fonction g")) test_conv() def test_back(): "Test la méthode de Newton-Raphson pour la fonctions f avec backtracking" x = np.arange(0.0, 6, 1) u = np.arange(0.0, 6, 1) v = np.arange(0.0, 6, 1) for i in np.arange(0,u.size): u[i] = np.linalg.norm(f_X(f,newton_raphson(f, J, U, i, epsilon),3,4)) for i in np.arange(0,v.size): v[i] = np.linalg.norm(f_X(f,newton_raphson_backtrack(f, J, U, i, epsilon),3,4)) plt.clf() k = plt.plot(x, u, linewidth=1.0) h = plt.plot(x, v, linewidth=1.0) plt.xlabel('Nombre iterations de la suite de Newton-Raphson') plt.ylabel('Norme de l\'image de la solution') plt.legend((k,h),("Sans backtracking","Avec backtracking")) test_back()
[ [ 1, 0, 0.0216, 0.0072, 0, 0.66, 0, 954, 0, 1, 0, 0, 954, 0, 0 ], [ 1, 0, 0.0288, 0.0072, 0, 0.66, 0.0278, 596, 0, 1, 0, 0, 596, 0, 0 ], [ 14, 0, 0.0432, 0.0072, 0, ...
[ "import numpy as np", "import matplotlib.pyplot as plt", "epsilon = 0.00000000000001", "nmax = 1000", "def newton_raphson(f, J, U0, N, epsilon):\n \"Implementation de la methode de newton-raphson pour une fonction f\"\n n = len(J[0]) #Dimension de l'espace de départ\n m = len(J) #Dimension de l'esp...
#lista = [2,40,1,30,5] #en c se usa un vector n+1 dimension def insertion_sort(list2): for i in range(1, len(list2)): j = i while j > 0 and list2[j] < list2[j-1]: list2[j], list2[j - 1] = list2[j-1], list2[j] #swap j -= 1 return list2 def posMenor(ls,i,n): posm = i for j in xrange(i+1,n): if ls[j] < ls [posm]: posm = j return posm def seleccion(ls): #en c, pasar n por parametro n=len(ls) for i in xrange(0,n): posm = posMenor(ls,i,n) #swap(ls[i],ls[posm]) ls[i], ls[posm] = ls[posm], ls[i] return ls def burbuja(ls): #en c, pasar n por parametro n=len(ls) for i in xrange(0,n-1): for j in xrange(i+1,n): if ls[i] > ls[j]: ls[i], ls[j] = ls[j], ls[i] return ls def shell_sort(lista): n=len(lista) k=n/2 while k>0: i=0 while i+k<n: if lista[i]>lista[i+k]: lista[i], lista[i+k] = lista[i+k], lista[i] #swap i += 1 k /= 2 return lista def quicksort(ls): size = len(ls) pivot = ls[size/2] i=0 j=size-1 while i<j: while ls[i] < pivot: i += 1 while ls[j] > pivot: j -= 1 ls[i], ls[j] = ls[j], ls[i] #swap return ls # mergesort def mergeSort(toSort): if len(toSort) <= 1: return toSort mIndex = len(toSort) / 2 left = mergeSort(toSort[:mIndex]) right = mergeSort(toSort[mIndex:]) result = [] while len(left) > 0 and len(right) > 0: if left[0] > right[0]: result.append(right.pop(0)) else: result.append(left.pop(0)) if len(left) > 0: result.extend(mergeSort(left)) else: result.extend(mergeSort(right)) return result #mergesort end #MAIN ls = [2,40,1,30,5] lsi = [2,40,1,30,5,0,15] #ls = [40,5] #ls = [5] print 'seleccion:', seleccion(ls) print 'burbuja:', burbuja(ls) print 'lsi:', lsi print 'insertion_sort:', insertion_sort(lsi) print 'shell_sort:', shell_sort(lsi) print 'quicksort: ', quicksort(ls) print 'mergesort:', mergeSort(lsi)
[ [ 2, 0, 0.0645, 0.0753, 0, 0.66, 0, 413, 0, 1, 1, 0, 0, 0, 2 ], [ 6, 1, 0.0645, 0.0538, 1, 0.69, 0, 826, 3, 0, 0, 0, 0, 0, 2 ], [ 14, 2, 0.0538, 0.0108, 2, 0.12, ...
[ "def insertion_sort(list2):\n for i in range(1, len(list2)):\n j = i\n while j > 0 and list2[j] < list2[j-1]:\n list2[j], list2[j - 1] = list2[j-1], list2[j] #swap\n j -= 1\n return list2", " for i in range(1, len(list2)):\n j = i\n while j > 0 and list...
def facorial(n): if n==1: return n return n*facorial(n-1) def multiplicar(a,b): if b==1: return a return a+multiplicar(a,b-1) def binario(n): if n != 0: binario(n/2) print str(n%2), def binario_ww(n): if n<2: print n%2, else: binario_ww(n/2) print n%2, def fibo(n): if n<=2: return n return fibo(n-1) + fibo(n-2) #main print multiplicar(4,3) print 'binario', binario(12) print '\nbinario_ww', binario_ww(12) print for x in xrange(1,10): print 'fibo:',x,', ', fibo(x) print 'factorial', facorial(5)
[ [ 2, 0, 0.0909, 0.0909, 0, 0.66, 0, 833, 0, 1, 1, 0, 0, 0, 1 ], [ 4, 1, 0.0909, 0.0303, 1, 0.55, 0, 0, 0, 0, 0, 0, 0, 0, 0 ], [ 13, 2, 0.0909, 0.0303, 2, 0.41, ...
[ "def facorial(n):\n if n==1: return n\n return n*facorial(n-1)", " if n==1: return n", " if n==1: return n", " return n*facorial(n-1)", "def multiplicar(a,b):\n if b==1:\n return a\n return a+multiplicar(a,b-1)", " if b==1:\n return a", " return a", " return a+multiplicar(a,b-1)", ...
#! /usr/bin/env python from random import randint from random import shuffle import math #n vertices y m aristas # u # b # k #defino el nombre de cada archivo fo = open("instancias.in", "wb") for q in range(500): n = randint(5,200) #calculo la cantidad de aristas del grafo completo completo = n*(n-1)*0.5 #aristas t = 1000 m = int(completo) #k = randint(1,t) u = randint(1,n) #nodo origen v = randint(1,n) # nodo destino while v == u: v = randint(1,n) lista = [] #las lineas de las aristas sumaW1 = 0 for i in range(1,n): for j in range(i+1,n+1): u1 = i v1 = j w1 = randint(1,int(t/10)) w2 = randint(1,int(t/10)) t1 = u1, v1, w1, w2 lista.append(t1) sumaW1 += w1 #cantidad de ejes que hay que atravesar aprox saltosAprox = math.copysign( 1, (u-v) ) * (u-v) #ajuste que hago del estima de saltos, Estimado * constante de ajuste C = 4 K = int( (saltosAprox * C) * ( sumaW1/m ) ) #print "estime un K %s de un grafo con promedio %d para distancia %s" % (K,sumaW1/m ,saltosAprox) shuffle(lista) # SI se quiere un grafo completo comentar esta linea. corte = int(completo * 3/4) del lista[corte:] #primer linea la cantidad de joyas n fo.write( str(n) + " " + str(len(lista)) + " " + str(u) + " " + str(v) + " " + str(K) + "\n") #fo.write( str(u1) + " " + str(v1) + " "+ str(w1)+ " " + str(w2) + "\n") for i in range(0,len(lista)): salida = lista[i] fo.write( str(salida[0]) + " " + str(salida[1]) + " " + str(salida[2]) + " " + str(salida[3]) + "\n") fo.write( "0") fo.close()
[ [ 1, 0, 0.05, 0.0167, 0, 0.66, 0, 715, 0, 1, 0, 0, 715, 0, 0 ], [ 1, 0, 0.0667, 0.0167, 0, 0.66, 0.1667, 715, 0, 1, 0, 0, 715, 0, 0 ], [ 1, 0, 0.0833, 0.0167, 0, 0....
[ "from random import randint", "from random import shuffle", "import math", "fo = open(\"instancias.in\", \"wb\")", "for q in range(500):\n n = randint(5,200)\n #calculo la cantidad de aristas del grafo completo\n completo = n*(n-1)*0.5\n #aristas\n t = 1000\n m = int(completo)\n #k = randint(1,t)", ...
#!/usr/bin/env python # -*- indent-tabs-mode: nil; tab-width: 4; coding: utf-8 -*- # vi: set ts=4 sts=4 sw=4 set smarttab set expandtab # http://www.careercup.com/question?id=15139669 """ Write a method that takes a camilCase string as a parameter and returns underscore_case as output. Assume that input can be null or empty. If CamilCase parametar starts with a capital letter turn it into lower case without puting underscore before it. How do you test this method? """ import os, re, sys, getopt import logging import locale from utils import * import copy @time_profile def camil_to_underscore_david(s): if not s: return s result = [] Z = ord('Z') s = [ord(c) for c in s] result = [s[0] <= Z and chr(s[0] + 32) or chr(s[0])] for i in range(1, len(s)): if s[i] <= Z: result.append('_') result.append(chr(s[i] + 32)) else: result.append(chr(s[i])) return "".join(result) @time_profile def camil_to_underscore_lobatt(s): if not s or len(s) <= 0: return s result = ""; ord_a = ord('a') ord_A = ord('A') for i in range(0, len(s)): ch = ord(s[i]) if ch < ord_A: result += s[i] elif ch < ord_a: if i != 0: result += '_' result += chr(ch + 32) else: result += s[i] return result if __name__ == '__main__': for i in range(0, 10): s = random_str(150) david = camil_to_underscore_david(s) lobatt = camil_to_underscore_lobatt(s) if david == lobatt: print_pass() else: print_fail() print s print david print lobatt
[ [ 8, 0, 0.1034, 0.0517, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 1, 0, 0.1552, 0.0172, 0, 0.66, 0.125, 688, 0, 4, 0, 0, 688, 0, 0 ], [ 1, 0, 0.1724, 0.0172, 0, 0.66,...
[ "\"\"\"\nWrite a method that takes a camilCase string as a parameter and returns underscore_case as output. Assume that input can be null or empty. If CamilCase parametar starts with a capital letter turn it into lower case without puting underscore before it. How do you test this method?\n\"\"\"", "import os, re...
#!/usr/bin/env python # -*- indent-tabs-mode: nil; tab-width: 4; coding: utf-8 -*- # vi: set ts=4 sts=4 sw=4 set smarttab set expandtab #http://www.careercup.com/question?id=14581715 #Google interview question """ Given an array of intergers. Write a program to print all the permutations of the numbers in the array. The output should be sorted in a non-increasing order. For example for the array { 12, 4, 66, 8, 9}, the output should be: 9866412 9866124 9846612 .... .... 1246689 """ import os, re, sys, getopt import time from utils import * def print_permutation_david_helper(prefix, arr, result): if not len(arr): result.append("".join(prefix)) return else: for i in range(0, len(arr)): prefix.append(arr[i]) del arr[i] print_permutation_david_helper(prefix, arr, result) arr.insert(i, prefix.pop()) @time_profile def print_permutations_david(arr): arr.sort(key = lambda x: str(x)) arr.reverse() arr = [str(i) for i in arr] result = [] print_permutation_david_helper([], arr, result) return result def permutation_helper(prefix, arr, result): if len(arr) > 0: permutation_helper(prefix + str(arr[-1]), arr[:-1], result) for i in range(len(arr) - 2, -1, -1): permutation_helper(prefix + str(arr[i]), arr[:i] + arr[i + 1:], result) else: result.append(prefix) @time_profile def print_permutations_lobatt(arr): if len(arr) <= 0: return a = sorted(arr, key=lambda x: str(x)) result = [] prefix = "" permutation_helper(prefix, a, result) return result if __name__ == '__main__': try: opts, args = getopt.getopt(sys.argv[1:], 'd:', ['date=', 'debug']) for opt, arg in opts: if opt in ['-d', '--date']: date = datetime.date(int(arg[:4]), int(arg[4:6]), int(arg[6:8])) elif opt in ['--debug']: debug = True except getopt.GetoptError, err: print str(err) print __doc__ sys.exit(1) for i in range(0, 15): arr = random_arr(10, 1, 20) arr = list(set(arr)) lobatt = print_permutations_lobatt(arr) david = print_permutations_david(arr) print arr if lobatt == david: print_pass() else: print_fail() print lobatt print david
[ [ 1, 0, 0.0244, 0.0244, 0, 0.66, 0, 688, 0, 4, 0, 0, 688, 0, 0 ], [ 1, 0, 0.0488, 0.0244, 0, 0.66, 0.1667, 654, 0, 1, 0, 0, 654, 0, 0 ], [ 1, 0, 0.0732, 0.0244, 0, ...
[ "import os, re, sys, getopt", "import time", "from utils import *", "def print_permutation_david_helper(prefix, arr, result):\n if not len(arr):\n result.append(\"\".join(prefix))\n return\n else:\n for i in range(0, len(arr)):\n prefix.append(arr[i])\n del arr...
#!/usr/bin/env python # -*- indent-tabs-mode: nil; tab-width: 4; coding: utf-8 -*- # vi: set ts=4 sts=4 sw=4 set smarttab set expandtab #http://www.careercup.com/question?id=15029918 #Google interview question """ Given two string S1 and S2. S1 contains from A-Z and S2 contains A-Z, * and ? Where * means any character 0 or any number of times Where ? means any character 0 or 1 number of times Write a program to determine whether S2 matches S1 """ import os, re, sys, getopt import logging import locale def is_match_lobatt(s, pattern): print "s=" + s + "\tpattern="+pattern if len(s) == 0: if pattern == '*' or pattern == '?': return True return False if len(pattern) == 0 or pattern == '*': return True i, j = 0, 0 while i < len(s) and j < len(pattern): if pattern[j] == '*': last = 0 k = i j += 1 if j >= len(pattern): return True while k < len(s): if(s[k] == pattern[j]): i = k k += 1 elif pattern[j] == '?': if j + 1 < len(pattern): if s[i] != pattern[j + 1]: i += 1 j += 1 elif pattern[j] == s[i]: j += 1 i += 1 else: return False if i == len(s) and j == len(pattern): return True return False def is_match_lobatt_2(s, pattern): print "s=" + s + "\tpattern="+pattern return is_match_lobatt_recur(s, pattern) def is_match_lobatt_recur(s, pattern): #print "s=" + s + "\tpattern="+pattern if len(s) == 0: if len(pattern) ==0 or pattern == '*' or pattern == '?': return True return False if len(pattern) == 0 or pattern == '*': return True i, j = 0, 0 if s[i] == pattern[j]: return is_match_lobatt_recur(s[1:],pattern[1:]) elif pattern[j] == '?': return is_match_lobatt_recur(s[1:],pattern[1:]) or is_match_lobatt_recur(s,pattern[1:]) elif pattern[j] == '*': if j + 1 >= len(pattern): return True for i in rang(0, len(s)): if is_match_lobatt_recur(s[i:],pattern[j + 1:]): return True return is_match_lobatt_recur(s,pattern[j + 1:]) else: return False def is_match_david_1(string, pattern, string_index, pattern_index): if string_index == len(string) and pattern_index == len(pattern): return True if pattern_index == len(pattern): return False if pattern[pattern_index] == '?': return is_match_david_1(string, pattern, string_index, pattern_index + 1) or is_match_david_1(string, pattern, string_index + 1, pattern_index + 1) if pattern[pattern_index] == '*': pre_char = -1 for i in range(string_index, len(string) + 1): if is_match_david_1(string, pattern, i, pattern_index + 1): return True if i == len(string) or pre_char != -1 and pre_char != string[i]: break pre_char = string[i] if string_index == len(string): return False if string[string_index] == pattern[pattern_index]: return is_match_david_1(string, pattern, string_index + 1, pattern_index + 1) return False def is_match_david(string, pattern): print "s=" + string + "\tpattern="+pattern return is_match_david_1(string, pattern, 0, 0) if __name__ == '__main__': try: opts, args = getopt.getopt(sys.argv[1:], 'd:', ['date=', 'debug']) for opt, arg in opts: if opt in ['-d', '--date']: date = datetime.date(int(arg[:4]), int(arg[4:6]), int(arg[6:8])) elif opt in ['--debug']: debug = True except getopt.GetoptError, err: print str(err) print __doc__ sys.exit(1) string = "abcsdedsds" pattern = "ab?sde*ds" print is_match_david(string, pattern)
[ [ 1, 0, 0.0133, 0.0133, 0, 0.66, 0, 688, 0, 4, 0, 0, 688, 0, 0 ], [ 1, 0, 0.0267, 0.0133, 0, 0.66, 0.1429, 715, 0, 1, 0, 0, 715, 0, 0 ], [ 1, 0, 0.04, 0.0133, 0, 0....
[ "import os, re, sys, getopt", "import logging", "import locale", "def is_match_lobatt(s, pattern):\n print(\"s=\" + s + \"\\tpattern=\"+pattern)\n if len(s) == 0:\n if pattern == '*' or pattern == '?': return True\n return False\n if len(pattern) == 0 or pattern == '*': return True\n ...
#!/usr/bin/env python # -*- indent-tabs-mode: nil; tab-width: 4; coding: utf-8 -*- # vi: set ts=4 sts=4 sw=4 set smarttab set expandtab # http://www.careercup.com/question?id=11532811 """ Given an array A[], find (i, j) such that A[i] < A[j] and (j - i) is maximum. """ from utils import * @time_profile def find_max_diff_david(A): if not A: return (0, 0) length = len(A) pre_sequences = [(A[0], 0)] suf_sequences = [(A[-1], length - 1)] for i in range(1, length): if A[i] < pre_sequences[-1][0]: pre_sequences.append((A[i], i)) for i in range(length - 2, -1, -1): if A[i] > suf_sequences[-1][0]: suf_sequences.append((A[i], i)) result = (-1, -1) for i in range(0, len(pre_sequences)): if result[1] - result[0] >= suf_sequences[0][1] - pre_sequences[i][1]: break for suffix in suf_sequences: if suffix[0] > pre_sequences[i][0]: if suffix[1] - pre_sequences[i][1] > result[1] - result[0]: result = (pre_sequences[i][1], suffix[1]) break return result @time_profile def find_max_diff_lobatt(A): maxdiff = len(A) - 1 for step in range(maxdiff, 0, -1): for i in range(0, len(A) - step): if A[step + i] > A[i]: return (i, step + i) return (-1, -1) @time_profile def find_max_diff_baseline(A): maxdiff,ti, tj = -1, -1, -1 for i in range(0, len(A)): for j in range(i, len(A)): if A[j] > A[i] and j - i > maxdiff: maxdiff = j - i ti = i tj = j return (ti, tj) if __name__ == '__main__': #Bad case below, what is the proper return value? #A = range(10000, 0, -1) A = random_arr(10000, 0, 10000) r1 = find_max_diff_david(A) r2 = find_max_diff_lobatt(A) r3 = find_max_diff_baseline(A) if r1 == r2 and r2 == r3: print_pass() else: print_fail() print A print r1 print r2
[ [ 8, 0, 0.0938, 0.0469, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 1, 0, 0.125, 0.0156, 0, 0.66, 0.2, 970, 0, 1, 0, 0, 970, 0, 0 ], [ 2, 0, 0.2969, 0.2656, 0, 0.66, ...
[ "\"\"\"\nGiven an array A[], find (i, j) such that A[i] < A[j] and (j - i) is maximum.\n\"\"\"", "from utils import *", "def find_max_diff_david(A):\n if not A: return (0, 0)\n length = len(A)\n pre_sequences = [(A[0], 0)]\n suf_sequences = [(A[-1], length - 1)]\n for i in range(1, length):\n ...
#!/usr/bin/env python # -*- indent-tabs-mode: nil; tab-width: 4; coding: utf-8 -*- # vi: set ts=4 sts=4 sw=4 set smarttab set expandtab # http://www.careercup.com/question?id=6227714491023360 ''' suppose a string is consists of a, b, and c Now given a integer N, output the amount of all possible strings of length N that don't of have consecutive a,b,c. e.g. given N=5, string bacca is invalid since the first 3 letters have consecutive a,b,c. and bbbbb is valid. ''' import os, re, sys, getopt import logging import locale from utils import * def all_possible_recur(full_set, n, s, result): #print s if len(s) == n: result.append(s) return size = len(full_set) valid_set = full_set exists = set() for i in xrange(len(s) -1, -1, -1): if s[i] in exists: break exists.add(s[i]) if len(full_set.difference(exists)) == 1: valid_set = exists break #print s #print valid_set #print for c in valid_set: all_possible_recur(full_set, n, s+c, result) return @time_profile def all_possible_lobatt(valid_set, n): result = [] all_possible_recur(valid_set, n, '', result) return sorted(result) def all_possible_david_help(valid_set, chars, n, result): if len(chars) == n: result.append("".join(chars)) else: start_index = max(len(chars) - 2, 0) knowns_chars = set([]) if len(chars): knowns_chars = set(chars[start_index:]) for ch in valid_set: if len(knowns_chars) == 2 and ch not in knowns_chars: continue chars.append(ch) all_possible_david_help(valid_set, chars, n, result) chars.pop() @time_profile def all_possible_david(valid_set, n): result = [] valid_set = set(valid_set) all_possible_david_help(valid_set, [], n, result) return sorted(result) if __name__ == '__main__': valid_set = {'a','b','c'} for i in range(3, 8): check_result(all_possible_david, all_possible_lobatt, (valid_set, i))
[ [ 8, 0, 0.1014, 0.0725, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 1, 0, 0.1594, 0.0145, 0, 0.66, 0.1111, 688, 0, 4, 0, 0, 688, 0, 0 ], [ 1, 0, 0.1739, 0.0145, 0, 0.66...
[ "'''\nsuppose a string is consists of a, b, and c \nNow given a integer N, output the amount of all possible strings of length N that don't of have consecutive a,b,c. \ne.g. given N=5, string bacca is invalid since the first 3 letters have consecutive a,b,c. and bbbbb is valid.\n'''", "import os, re, sys, getopt"...
#!/usr/bin/env python # -*- indent-tabs-mode: nil; tab-width: 4; coding: utf-8 -*- # vi: set ts=4 sts=4 sw=4 set smarttab set expandtab # http://www.careercup.com/question?id=15139669 """ Write a method that takes a camilCase string as a parameter and returns underscore_case as output. Assume that input can be null or empty. If CamilCase parametar starts with a capital letter turn it into lower case without puting underscore before it. How do you test this method? """ import os, re, sys, getopt import logging import locale from utils import * import copy @time_profile def camil_to_underscore_david(s): if not s: return s result = [] Z = ord('Z') s = [ord(c) for c in s] result = [s[0] <= Z and chr(s[0] + 32) or chr(s[0])] for i in range(1, len(s)): if s[i] <= Z: result.append('_') result.append(chr(s[i] + 32)) else: result.append(chr(s[i])) return "".join(result) @time_profile def camil_to_underscore_lobatt(s): if not s or len(s) <= 0: return s result = ""; ord_a = ord('a') ord_A = ord('A') for i in range(0, len(s)): ch = ord(s[i]) if ch < ord_A: result += s[i] elif ch < ord_a: if i != 0: result += '_' result += chr(ch + 32) else: result += s[i] return result if __name__ == '__main__': for i in range(0, 10): s = random_str(150) david = camil_to_underscore_david(s) lobatt = camil_to_underscore_lobatt(s) if david == lobatt: print_pass() else: print_fail() print s print david print lobatt
[ [ 8, 0, 0.1034, 0.0517, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 1, 0, 0.1552, 0.0172, 0, 0.66, 0.125, 688, 0, 4, 0, 0, 688, 0, 0 ], [ 1, 0, 0.1724, 0.0172, 0, 0.66,...
[ "\"\"\"\nWrite a method that takes a camilCase string as a parameter and returns underscore_case as output. Assume that input can be null or empty. If CamilCase parametar starts with a capital letter turn it into lower case without puting underscore before it. How do you test this method?\n\"\"\"", "import os, re...
#!/usr/bin/env python # -*- indent-tabs-mode: nil; tab-width: 4; coding: utf-8 -*- # vi: set ts=4 sts=4 sw=4 set smarttab set expandtab #http://www.careercup.com/question?id=14581715 #Google interview question """ Given an array of intergers. Write a program to print all the permutations of the numbers in the array. The output should be sorted in a non-increasing order. For example for the array { 12, 4, 66, 8, 9}, the output should be: 9866412 9866124 9846612 .... .... 1246689 """ import os, re, sys, getopt import time from utils import * def print_permutation_david_helper(prefix, arr, result): if not len(arr): result.append("".join(prefix)) return else: for i in range(0, len(arr)): prefix.append(arr[i]) del arr[i] print_permutation_david_helper(prefix, arr, result) arr.insert(i, prefix.pop()) @time_profile def print_permutations_david(arr): arr.sort(key = lambda x: str(x)) arr.reverse() arr = [str(i) for i in arr] result = [] print_permutation_david_helper([], arr, result) return result def permutation_helper(prefix, arr, result): if len(arr) > 0: permutation_helper(prefix + str(arr[-1]), arr[:-1], result) for i in range(len(arr) - 2, -1, -1): permutation_helper(prefix + str(arr[i]), arr[:i] + arr[i + 1:], result) else: result.append(prefix) @time_profile def print_permutations_lobatt(arr): if len(arr) <= 0: return a = sorted(arr, key=lambda x: str(x)) result = [] prefix = "" permutation_helper(prefix, a, result) return result if __name__ == '__main__': try: opts, args = getopt.getopt(sys.argv[1:], 'd:', ['date=', 'debug']) for opt, arg in opts: if opt in ['-d', '--date']: date = datetime.date(int(arg[:4]), int(arg[4:6]), int(arg[6:8])) elif opt in ['--debug']: debug = True except getopt.GetoptError, err: print str(err) print __doc__ sys.exit(1) for i in range(0, 15): arr = random_arr(10, 1, 20) arr = list(set(arr)) lobatt = print_permutations_lobatt(arr) david = print_permutations_david(arr) print arr if lobatt == david: print_pass() else: print_fail() print lobatt print david
[ [ 1, 0, 0.0244, 0.0244, 0, 0.66, 0, 688, 0, 4, 0, 0, 688, 0, 0 ], [ 1, 0, 0.0488, 0.0244, 0, 0.66, 0.1667, 654, 0, 1, 0, 0, 654, 0, 0 ], [ 1, 0, 0.0732, 0.0244, 0, ...
[ "import os, re, sys, getopt", "import time", "from utils import *", "def print_permutation_david_helper(prefix, arr, result):\n if not len(arr):\n result.append(\"\".join(prefix))\n return\n else:\n for i in range(0, len(arr)):\n prefix.append(arr[i])\n del arr...
#!/usr/bin/env python # -*- indent-tabs-mode: nil; tab-width: 4; coding: utf-8 -*- # vi: set ts=4 sts=4 sw=4 set smarttab set expandtab # http://www.careercup.com/question?id=11532811 """ Given an array A[], find (i, j) such that A[i] < A[j] and (j - i) is maximum. """ from utils import * @time_profile def find_max_diff_david(A): if not A: return (0, 0) length = len(A) pre_sequences = [(A[0], 0)] suf_sequences = [(A[-1], length - 1)] for i in range(1, length): if A[i] < pre_sequences[-1][0]: pre_sequences.append((A[i], i)) for i in range(length - 2, -1, -1): if A[i] > suf_sequences[-1][0]: suf_sequences.append((A[i], i)) result = (-1, -1) for i in range(0, len(pre_sequences)): if result[1] - result[0] >= suf_sequences[0][1] - pre_sequences[i][1]: break for suffix in suf_sequences: if suffix[0] > pre_sequences[i][0]: if suffix[1] - pre_sequences[i][1] > result[1] - result[0]: result = (pre_sequences[i][1], suffix[1]) break return result @time_profile def find_max_diff_lobatt(A): maxdiff = len(A) - 1 for step in range(maxdiff, 0, -1): for i in range(0, len(A) - step): if A[step + i] > A[i]: return (i, step + i) return (-1, -1) @time_profile def find_max_diff_baseline(A): maxdiff,ti, tj = -1, -1, -1 for i in range(0, len(A)): for j in range(i, len(A)): if A[j] > A[i] and j - i > maxdiff: maxdiff = j - i ti = i tj = j return (ti, tj) if __name__ == '__main__': #Bad case below, what is the proper return value? #A = range(10000, 0, -1) A = random_arr(10000, 0, 10000) r1 = find_max_diff_david(A) r2 = find_max_diff_lobatt(A) r3 = find_max_diff_baseline(A) if r1 == r2 and r2 == r3: print_pass() else: print_fail() print A print r1 print r2
[ [ 8, 0, 0.0938, 0.0469, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 1, 0, 0.125, 0.0156, 0, 0.66, 0.2, 970, 0, 1, 0, 0, 970, 0, 0 ], [ 2, 0, 0.2969, 0.2656, 0, 0.66, ...
[ "\"\"\"\nGiven an array A[], find (i, j) such that A[i] < A[j] and (j - i) is maximum.\n\"\"\"", "from utils import *", "def find_max_diff_david(A):\n if not A: return (0, 0)\n length = len(A)\n pre_sequences = [(A[0], 0)]\n suf_sequences = [(A[-1], length - 1)]\n for i in range(1, length):\n ...
#!/usr/bin/env python # -*- indent-tabs-mode: nil; tab-width: 4; coding: utf-8 -*- # vi: set ts=4 sts=4 sw=4 set smarttab set expandtab # http://www.careercup.com/question?id=6227714491023360 ''' suppose a string is consists of a, b, and c Now given a integer N, output the amount of all possible strings of length N that don't of have consecutive a,b,c. e.g. given N=5, string bacca is invalid since the first 3 letters have consecutive a,b,c. and bbbbb is valid. ''' import os, re, sys, getopt import logging import locale from utils import * def all_possible_recur(full_set, n, s, result): #print s if len(s) == n: result.append(s) return size = len(full_set) valid_set = full_set exists = set() for i in xrange(len(s) -1, -1, -1): if s[i] in exists: break exists.add(s[i]) if len(full_set.difference(exists)) == 1: valid_set = exists break #print s #print valid_set #print for c in valid_set: all_possible_recur(full_set, n, s+c, result) return @time_profile def all_possible_lobatt(valid_set, n): result = [] all_possible_recur(valid_set, n, '', result) return sorted(result) def all_possible_david_help(valid_set, chars, n, result): if len(chars) == n: result.append("".join(chars)) else: start_index = max(len(chars) - 2, 0) knowns_chars = set([]) if len(chars): knowns_chars = set(chars[start_index:]) for ch in valid_set: if len(knowns_chars) == 2 and ch not in knowns_chars: continue chars.append(ch) all_possible_david_help(valid_set, chars, n, result) chars.pop() @time_profile def all_possible_david(valid_set, n): result = [] valid_set = set(valid_set) all_possible_david_help(valid_set, [], n, result) return sorted(result) if __name__ == '__main__': valid_set = {'a','b','c'} for i in range(3, 8): check_result(all_possible_david, all_possible_lobatt, (valid_set, i))
[ [ 8, 0, 0.1014, 0.0725, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 1, 0, 0.1594, 0.0145, 0, 0.66, 0.1111, 688, 0, 4, 0, 0, 688, 0, 0 ], [ 1, 0, 0.1739, 0.0145, 0, 0.66...
[ "'''\nsuppose a string is consists of a, b, and c \nNow given a integer N, output the amount of all possible strings of length N that don't of have consecutive a,b,c. \ne.g. given N=5, string bacca is invalid since the first 3 letters have consecutive a,b,c. and bbbbb is valid.\n'''", "import os, re, sys, getopt"...
#!/usr/bin/env python # -*- indent-tabs-mode: nil; tab-width: 4; coding: utf-8 -*- # vi: set ts=4 sts=4 sw=4 set smarttab set expandtab #http://www.careercup.com/question?id=14991189 #Google interview question """ Design an algorithm that, given a list of n elements in an array, finds all the elements that appear more than n/3 times in the list. The algorithm should run in linear time. (n >=0 ) You are expected to use comparisons and achieve linear time. No hashing/excessive space/ and don't use standard linear time deterministic selection algo """ from collections import defaultdict def find_elements(arr): counter = defaultdict(int) for i in arr: counter[i] += 1 if len(counter) < 3: continue for k in counter.keys(): if counter[k] == 1: del counter[k] else: counter[k] -= 1 for k in counter.iterkeys(): counter[k] = 0 for i in arr: if i in counter: counter[i] += 1 result = [] for k, count in counter.iteritems(): if count > len(arr) / 3: result.append(k) return result from utils import * arr = random_arr(16, 0, 4) print arr print find_elements(arr)
[ [ 8, 0, 0.2414, 0.1034, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 1, 0, 0.3103, 0.0345, 0, 0.66, 0.1667, 193, 0, 1, 0, 0, 193, 0, 0 ], [ 2, 0, 0.5862, 0.5172, 0, 0.66...
[ "\"\"\"\nDesign an algorithm that, given a list of n elements in an array, finds all the elements that appear more than n/3 times in the list. The algorithm should run in linear time. (n >=0 ) You are expected to use comparisons and achieve linear time. No hashing/excessive space/ and don't use standard linear time...
#!/usr/bin/env python # -*- indent-tabs-mode: nil; tab-width: 4; coding: utf-8 -*- # vi: set ts=4 sts=4 sw=4 set smarttab set expandtab # http://www.careercup.com/question?id=5361917182869504 """ a 32-bit integer could be splited into 32 small integers as: 1. bit 0~4 2. bit 1~5 ... 31. bit 30~31 and bit 0~2 32. bit 31 and bit 0~3 please find a 32-bit integer that could be splited into exactly 0~31 (the order doesn't matter). """ import os, re, sys, getopt import logging import locale import copy from utils import * def search_append_zero(seed, head, tail, seem): target = (tail * 2 )% 32 #print "==>target %s"%target if seem[target] == True: return seed else: new = copy.copy(seem) new[target] = True return search(seed + '0', head, target, new) def search_append_one(seed, head, tail, seem): target = (tail * 2 + 1)% 32 #print "==>target %s"%target if seem[target] == True: return seed else: new = copy.copy(seem) new[target] = True return search(seed + '1', head, target, new) def search_prepend_zero(seed, head, tail, seem): target = (head / 2 ) #print "==>target %s"%target if seem[target] == True: return seed else: new = copy.copy(seem) new[target] = True return search('0' + seed, target, tail, new) def search_prepend_one(seed, head, tail, seem): target = (head / 2 + 16 ) #print "==>target %s"%target if seem[target] == True: return seed else: new = copy.copy(seem) new[target] = True return search('1' + seed , target, tail, new) def search(seed, head, tail, seem): """docstring for search""" #print seed if len(seed) == 36 and seed[:4] == seed[32:]: return seed new = search_append_zero(seed, head, tail, seem) if len(new) == 36 and new[:4] == new[32:]: return new new = search_append_one(seed, head, tail, seem) if len(new) == 36 and new[:4] == new[32:]: return new new = search_prepend_zero(seed, head, tail, seem) if len(new) == 36 and new[:4] == new[32:]: return new new = search_prepend_one(seed, head, tail, seem) if len(new) == 36 and new[:4] == new[32:]: return new return seed @time_profile def search_profile(): seem = {} for i in xrange(0,32): seem[i] = False seem[0] = True return search("00000", 0, 0, seem) def string_to_int(s): i = 0 for k in xrange(0,len(s)): i *= 2 if s[k] == '1': i = i+1 return i if __name__ == '__main__': result = search_profile() print result[:32] for i in xrange(0,32): print result[i:i+5], print "-->", print string_to_int(result[i:i+5])
[ [ 8, 0, 0.0957, 0.0957, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 1, 0, 0.1489, 0.0106, 0, 0.66, 0.0769, 688, 0, 4, 0, 0, 688, 0, 0 ], [ 1, 0, 0.1596, 0.0106, 0, 0.66...
[ "\"\"\"\na 32-bit integer could be splited into 32 small integers as: \n 1. bit 0~4 \n 2. bit 1~5 \n ... \n 31. bit 30~31 and bit 0~2 \n 32. bit 31 and bit 0~3 \n please find a 32-bit integer that could be splited into exactly 0~31 (the order doesn't matter).", "import os, re, sys, getopt", "i...
#!/usr/bin/env python # -*- indent-tabs-mode: nil; tab-width: 4; coding: utf-8 -*- # vi: set ts=4 sts=4 sw=4 set smarttab set expandtab # http://www.careercup.com/question?id=14813758 """ Given 2 arrays A,B, where x(A.length) < y(B.length), we want to insert (y - x) 0's to A at various places such that A*B is minimum. For instance, if A = (1, -1) and B = (1,2, 3, 4), then inserting two 0's in the middle of A such that A = (1, 0, 0, -1) would minimize A*B. I think he was looking for a dynamic problem solution. """ import os, re, sys, getopt import logging import locale def min_multi_helper(A, B, i, j, matrix, positions): if (i, j) in matrix: return matrix[(i, j)] result = 0 if i == j - 1: result, positions[(i, j)] = 0, 0 elif j == 0: result = B[i] * A[i] if i != 0: result += min_multi_helper(A, B, i - 1, 0, matrix, positions) positions[(i, j)] = A[i] else: fill_0, fill_non_0 = min_multi_helper(A, B, i - 1, j - 1, matrix, positions), B[i] * A[i - j] + min_multi_helper(A, B, i - 1, j, matrix, positions) if fill_0 < fill_non_0: result, positions[(i, j)] = fill_0, 0 else: result, positions[(i, j)] = fill_non_0, A[i - j] matrix[(i, j)] = result return result def min_multi_david(A, B): matrix, positions = {}, {} result = min_multi_helper(A, B, len(B) - 1, len(B) - len(A), matrix, positions) #print positions return result def min_multi_lobatt(a, b): if len(a) < len(b): return 0, [] zeros = len(a) - len(b) m = [] for i in range(0, (len(b)+1)): m.append([0] * (zeros + 1)) import copy r = copy.deepcopy(m) m[0][0] = 0 for i in range(1, len(b) + 1): m[i][0] = m[i - 1][0] + a[i - 1] * b[i - 1] for i in range(1, len(b) + 1): for j in range(1, zeros + 1): r[i][j] = m[i][j - 1] < a[i + j - 1] * b[i - 1] + m[i -1][j] and r[i][j - 1] + 1 or 0 m[i][j] = min(m[i][j - 1], a[i + j - 1] * b[i -1] + m[i -1][j]) #print_matrix(r) #print_matrix(m) i = len(b) j = zeros result = [] while i > 0: if r[i][j] > 0: result.extend([0] * r[i][j]) j -= r[i][j] else: result.append(b[i - 1]) i -= 1 result.extend([0] * (len(a) - len(result))) return m[len(b)][zeros], result[::-1] if __name__ == '__main__': from utils import * for i in range(0, 10): A = random_arr(4, -2, 5) B = random_arr(8, -1, 6) david = min_multi_david(A, B) lobatt, dummy = min_multi_lobatt(B, A) if david != lobatt: print A print B print david print lobatt else: print A print B print "PASS" print ""
[ [ 8, 0, 0.0872, 0.0698, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 1, 0, 0.1279, 0.0116, 0, 0.66, 0.1429, 688, 0, 4, 0, 0, 688, 0, 0 ], [ 1, 0, 0.1395, 0.0116, 0, 0.66...
[ "\"\"\"\nGiven 2 arrays A,B, where x(A.length) < y(B.length), we want to\ninsert (y - x) 0's to A at various places such that A*B is minimum. For instance, if A = (1, -1) and\nB = (1,2, 3, 4), then inserting two 0's in the middle of A such that A = (1, 0, 0, -1) would minimize\nA*B. I think he was looking for a dyn...
#!/usr/bin/env python # -*- indent-tabs-mode: nil; tab-width: 4; coding: utf-8 -*- # vi: set ts=4 sts=4 sw=4 set smarttab set expandtab # http://www.careercup.com/question?id=14736688 """ The maximum suffix of a string is the lexicographically largest suffix of the string. The maximum suffix problem is to find the maximum suffix of a given string. Linear time algorithm required. """ import os, re, sys, getopt import logging import locale from utils import * import copy @time_profile def get_max_suffix_david(s): if not s: return s max_indexes = [i for i in range(0, len(s))] max_length = 0 while len(max_indexes) > 1: max_char, new_indexes = -1, [] for index in max_indexes: if index + max_length >= len(s): break if s[index + max_length] > max_char: new_indexes = [] new_indexes.append(index) max_char = s[index + max_length] elif s[index + max_length] == max_char: new_indexes.append(index) max_length += 1 max_indexes, pre_index = [], 0 max_sequences, sequences = 1, 1 for i, index in enumerate(new_indexes): if i == 0: continue if index == new_indexes[i - 1] + max_length: sequences += 1 else: if sequences > max_sequences: max_indexes, max_sequences = [new_indexes[i - sequences]], sequences elif sequences == max_sequences: max_indexes.append(new_indexes[i - sequences]) sequences = 1 if sequences == max_sequences: max_indexes.append(new_indexes[len(new_indexes) - sequences]) elif sequences > max_sequences: max_indexes, max_sequences = [new_indexes[len(new_indexes) - sequences]], sequences max_length *= max_sequences return s[max_indexes[0]:] def max_suffix_duval(a,r0, n): r, s, m, d = r0, r0 + 1, 1, 0 M = [0] * (n + 2) M[1] = 1 while s < n: if a[s] < a[s - m]: s += 1 m = s - r M[m] = m elif a[s] == a[s-m]: s += 1 M[s - r] = m else: #print "==>\t", #print r, s, m #print "==>\t", #print M d = (s - r ) % m if d > 0: r = s -d m = M[d] else: r = s s += 1 m = 1 return a[r:] @time_profile def get_max_suffix_lobatt(s): return max_suffix_duval(s, 0, len(s)) if __name__ == '__main__': for i in range(0, 15): arr = random_arr(15, 0, 7) s = arr_to_str(arr) david, lobatt = get_max_suffix_david(s), get_max_suffix_lobatt(s) print s if david != lobatt: print "FAILed" print get_max_suffix_david(s) print get_max_suffix_lobatt(s) else: print "PASS" print ""
[ [ 8, 0, 0.0684, 0.0421, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 1, 0, 0.1053, 0.0105, 0, 0.66, 0.1111, 688, 0, 4, 0, 0, 688, 0, 0 ], [ 1, 0, 0.1158, 0.0105, 0, 0.66...
[ "\"\"\"\nThe maximum suffix of a string is the lexicographically largest suffix of the string. The maximum\nsuffix problem is to find the maximum suffix of a given string. Linear time algorithm required.\n\"\"\"", "import os, re, sys, getopt", "import logging", "import locale", "from utils import *", "imp...
#!/usr/bin/env python # -*- indent-tabs-mode: nil; tab-width: 4; coding: utf-8 -*- # vi: set ts=4 sts=4 sw=4 set smarttab set expandtab #http://www.careercup.com/question?id=15029918 #Google interview question """ Given two string S1 and S2. S1 contains from A-Z and S2 contains A-Z, * and ? Where * means any character 0 or any number of times Where ? means any character 0 or 1 number of times Write a program to determine whether S2 matches S1 """ import os, re, sys, getopt import logging import locale def is_match_lobatt(s, pattern): print "s=" + s + "\tpattern="+pattern if len(s) == 0: if pattern == '*' or pattern == '?': return True return False if len(pattern) == 0 or pattern == '*': return True i, j = 0, 0 while i < len(s) and j < len(pattern): if pattern[j] == '*': last = 0 k = i j += 1 if j >= len(pattern): return True while k < len(s): if(s[k] == pattern[j]): i = k k += 1 elif pattern[j] == '?': if j + 1 < len(pattern): if s[i] != pattern[j + 1]: i += 1 j += 1 elif pattern[j] == s[i]: j += 1 i += 1 else: return False if i == len(s) and j == len(pattern): return True return False def is_match_lobatt_2(s, pattern): print "s=" + s + "\tpattern="+pattern return is_match_lobatt_recur(s, pattern) def is_match_lobatt_recur(s, pattern): #print "s=" + s + "\tpattern="+pattern if len(s) == 0: if len(pattern) ==0 or pattern == '*' or pattern == '?': return True return False if len(pattern) == 0 or pattern == '*': return True i, j = 0, 0 if s[i] == pattern[j]: return is_match_lobatt_recur(s[1:],pattern[1:]) elif pattern[j] == '?': return is_match_lobatt_recur(s[1:],pattern[1:]) or is_match_lobatt_recur(s,pattern[1:]) elif pattern[j] == '*': if j + 1 >= len(pattern): return True for i in rang(0, len(s)): if is_match_lobatt_recur(s[i:],pattern[j + 1:]): return True return is_match_lobatt_recur(s,pattern[j + 1:]) else: return False def is_match_david_1(string, pattern, string_index, pattern_index): if string_index == len(string) and pattern_index == len(pattern): return True if pattern_index == len(pattern): return False if pattern[pattern_index] == '?': return is_match_david_1(string, pattern, string_index, pattern_index + 1) or is_match_david_1(string, pattern, string_index + 1, pattern_index + 1) if pattern[pattern_index] == '*': pre_char = -1 for i in range(string_index, len(string) + 1): if is_match_david_1(string, pattern, i, pattern_index + 1): return True if i == len(string) or pre_char != -1 and pre_char != string[i]: break pre_char = string[i] if string_index == len(string): return False if string[string_index] == pattern[pattern_index]: return is_match_david_1(string, pattern, string_index + 1, pattern_index + 1) return False def is_match_david(string, pattern): print "s=" + string + "\tpattern="+pattern return is_match_david_1(string, pattern, 0, 0) if __name__ == '__main__': try: opts, args = getopt.getopt(sys.argv[1:], 'd:', ['date=', 'debug']) for opt, arg in opts: if opt in ['-d', '--date']: date = datetime.date(int(arg[:4]), int(arg[4:6]), int(arg[6:8])) elif opt in ['--debug']: debug = True except getopt.GetoptError, err: print str(err) print __doc__ sys.exit(1) string = "abcsdedsds" pattern = "ab?sde*ds" print is_match_david(string, pattern)
[ [ 1, 0, 0.0133, 0.0133, 0, 0.66, 0, 688, 0, 4, 0, 0, 688, 0, 0 ], [ 1, 0, 0.0267, 0.0133, 0, 0.66, 0.1429, 715, 0, 1, 0, 0, 715, 0, 0 ], [ 1, 0, 0.04, 0.0133, 0, 0....
[ "import os, re, sys, getopt", "import logging", "import locale", "def is_match_lobatt(s, pattern):\n print(\"s=\" + s + \"\\tpattern=\"+pattern)\n if len(s) == 0:\n if pattern == '*' or pattern == '?': return True\n return False\n if len(pattern) == 0 or pattern == '*': return True\n ...
#!/usr/bin/env python # -*- indent-tabs-mode: nil; tab-width: 4; coding: utf-8 -*- # vi: set ts=4 sts=4 sw=4 set smarttab set expandtab #http://www.careercup.com/question?id=14851686 #Facebook interview question import random import time def random_arr(length = random.randint(10, 20), min = 0, max = 100): result = [random.randint(min, max) for i in range(length)] return result def random_str(length = random.randint(10, 20), chars = None): a, A = ord('a'), ord('A') if not chars: chars = [chr(i + a) for i in range(26)] + [chr(i + A) for i in range(26)] candidates_length = len(chars) result = [chars[random.randint(0, candidates_length - 1)] for i in range(length)] return "".join(result) def arr_to_str(arr): return "".join([chr(i + ord('a')) for i in arr]) def print_pass(): print '\x1b[32m PASS \x1b[0m' def print_fail(): print '\x1b[31m FAIL \x1b[0m' def time_profile(func): def timing_and_call(*args, **kwargs): start_time = time.time() try: return func(*args, **kwargs) finally: print func.__name__, ' running time: ', (time.time() - start_time) * 1000 , ' ms' return timing_and_call def check_result(david, lobatt, args): david = david(*args) lobatt = lobatt(*args) if david != lobatt: print_fail() print "david", david print "lobatt", lobatt else: print_pass()
[ [ 1, 0, 0.1458, 0.0208, 0, 0.66, 0, 715, 0, 1, 0, 0, 715, 0, 0 ], [ 1, 0, 0.1667, 0.0208, 0, 0.66, 0.125, 654, 0, 1, 0, 0, 654, 0, 0 ], [ 2, 0, 0.2292, 0.0625, 0, 0...
[ "import random", "import time", "def random_arr(length = random.randint(10, 20), min = 0, max = 100):\n result = [random.randint(min, max) for i in range(length)]\n return result", " result = [random.randint(min, max) for i in range(length)]", " return result", "def random_str(length = random....
#!/usr/bin/env python # -*- indent-tabs-mode: nil; tab-width: 4; coding: utf-8 -*- # vi: set ts=4 sts=4 sw=4 set smarttab set expandtab # http://www.careercup.com/question?id=5361917182869504 """ a 32-bit integer could be splited into 32 small integers as: 1. bit 0~4 2. bit 1~5 ... 31. bit 30~31 and bit 0~2 32. bit 31 and bit 0~3 please find a 32-bit integer that could be splited into exactly 0~31 (the order doesn't matter). """ import os, re, sys, getopt import logging import locale import copy from utils import * def search_append_zero(seed, head, tail, seem): target = (tail * 2 )% 32 #print "==>target %s"%target if seem[target] == True: return seed else: new = copy.copy(seem) new[target] = True return search(seed + '0', head, target, new) def search_append_one(seed, head, tail, seem): target = (tail * 2 + 1)% 32 #print "==>target %s"%target if seem[target] == True: return seed else: new = copy.copy(seem) new[target] = True return search(seed + '1', head, target, new) def search_prepend_zero(seed, head, tail, seem): target = (head / 2 ) #print "==>target %s"%target if seem[target] == True: return seed else: new = copy.copy(seem) new[target] = True return search('0' + seed, target, tail, new) def search_prepend_one(seed, head, tail, seem): target = (head / 2 + 16 ) #print "==>target %s"%target if seem[target] == True: return seed else: new = copy.copy(seem) new[target] = True return search('1' + seed , target, tail, new) def search(seed, head, tail, seem): """docstring for search""" #print seed if len(seed) == 36 and seed[:4] == seed[32:]: return seed new = search_append_zero(seed, head, tail, seem) if len(new) == 36 and new[:4] == new[32:]: return new new = search_append_one(seed, head, tail, seem) if len(new) == 36 and new[:4] == new[32:]: return new new = search_prepend_zero(seed, head, tail, seem) if len(new) == 36 and new[:4] == new[32:]: return new new = search_prepend_one(seed, head, tail, seem) if len(new) == 36 and new[:4] == new[32:]: return new return seed @time_profile def search_profile(): seem = {} for i in xrange(0,32): seem[i] = False seem[0] = True return search("00000", 0, 0, seem) def string_to_int(s): i = 0 for k in xrange(0,len(s)): i *= 2 if s[k] == '1': i = i+1 return i if __name__ == '__main__': result = search_profile() print result[:32] for i in xrange(0,32): print result[i:i+5], print "-->", print string_to_int(result[i:i+5])
[ [ 8, 0, 0.0957, 0.0957, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 1, 0, 0.1489, 0.0106, 0, 0.66, 0.0769, 688, 0, 4, 0, 0, 688, 0, 0 ], [ 1, 0, 0.1596, 0.0106, 0, 0.66...
[ "\"\"\"\na 32-bit integer could be splited into 32 small integers as: \n 1. bit 0~4 \n 2. bit 1~5 \n ... \n 31. bit 30~31 and bit 0~2 \n 32. bit 31 and bit 0~3 \n please find a 32-bit integer that could be splited into exactly 0~31 (the order doesn't matter).", "import os, re, sys, getopt", "i...
#!/usr/bin/env python # -*- indent-tabs-mode: nil; tab-width: 4; coding: utf-8 -*- # vi: set ts=4 sts=4 sw=4 set smarttab set expandtab # http://www.careercup.com/question?id=14736688 """ The maximum suffix of a string is the lexicographically largest suffix of the string. The maximum suffix problem is to find the maximum suffix of a given string. Linear time algorithm required. """ import os, re, sys, getopt import logging import locale from utils import * import copy @time_profile def get_max_suffix_david(s): if not s: return s max_indexes = [i for i in range(0, len(s))] max_length = 0 while len(max_indexes) > 1: max_char, new_indexes = -1, [] for index in max_indexes: if index + max_length >= len(s): break if s[index + max_length] > max_char: new_indexes = [] new_indexes.append(index) max_char = s[index + max_length] elif s[index + max_length] == max_char: new_indexes.append(index) max_length += 1 max_indexes, pre_index = [], 0 max_sequences, sequences = 1, 1 for i, index in enumerate(new_indexes): if i == 0: continue if index == new_indexes[i - 1] + max_length: sequences += 1 else: if sequences > max_sequences: max_indexes, max_sequences = [new_indexes[i - sequences]], sequences elif sequences == max_sequences: max_indexes.append(new_indexes[i - sequences]) sequences = 1 if sequences == max_sequences: max_indexes.append(new_indexes[len(new_indexes) - sequences]) elif sequences > max_sequences: max_indexes, max_sequences = [new_indexes[len(new_indexes) - sequences]], sequences max_length *= max_sequences return s[max_indexes[0]:] def max_suffix_duval(a,r0, n): r, s, m, d = r0, r0 + 1, 1, 0 M = [0] * (n + 2) M[1] = 1 while s < n: if a[s] < a[s - m]: s += 1 m = s - r M[m] = m elif a[s] == a[s-m]: s += 1 M[s - r] = m else: #print "==>\t", #print r, s, m #print "==>\t", #print M d = (s - r ) % m if d > 0: r = s -d m = M[d] else: r = s s += 1 m = 1 return a[r:] @time_profile def get_max_suffix_lobatt(s): return max_suffix_duval(s, 0, len(s)) if __name__ == '__main__': for i in range(0, 15): arr = random_arr(15, 0, 7) s = arr_to_str(arr) david, lobatt = get_max_suffix_david(s), get_max_suffix_lobatt(s) print s if david != lobatt: print "FAILed" print get_max_suffix_david(s) print get_max_suffix_lobatt(s) else: print "PASS" print ""
[ [ 8, 0, 0.0684, 0.0421, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 1, 0, 0.1053, 0.0105, 0, 0.66, 0.1111, 688, 0, 4, 0, 0, 688, 0, 0 ], [ 1, 0, 0.1158, 0.0105, 0, 0.66...
[ "\"\"\"\nThe maximum suffix of a string is the lexicographically largest suffix of the string. The maximum\nsuffix problem is to find the maximum suffix of a given string. Linear time algorithm required.\n\"\"\"", "import os, re, sys, getopt", "import logging", "import locale", "from utils import *", "imp...
#!/usr/bin/env python # -*- indent-tabs-mode: nil; tab-width: 4; coding: utf-8 -*- # vi: set ts=4 sts=4 sw=4 set smarttab set expandtab # http://www.careercup.com/question?id=14813758 """ Given 2 arrays A,B, where x(A.length) < y(B.length), we want to insert (y - x) 0's to A at various places such that A*B is minimum. For instance, if A = (1, -1) and B = (1,2, 3, 4), then inserting two 0's in the middle of A such that A = (1, 0, 0, -1) would minimize A*B. I think he was looking for a dynamic problem solution. """ import os, re, sys, getopt import logging import locale def min_multi_helper(A, B, i, j, matrix, positions): if (i, j) in matrix: return matrix[(i, j)] result = 0 if i == j - 1: result, positions[(i, j)] = 0, 0 elif j == 0: result = B[i] * A[i] if i != 0: result += min_multi_helper(A, B, i - 1, 0, matrix, positions) positions[(i, j)] = A[i] else: fill_0, fill_non_0 = min_multi_helper(A, B, i - 1, j - 1, matrix, positions), B[i] * A[i - j] + min_multi_helper(A, B, i - 1, j, matrix, positions) if fill_0 < fill_non_0: result, positions[(i, j)] = fill_0, 0 else: result, positions[(i, j)] = fill_non_0, A[i - j] matrix[(i, j)] = result return result def min_multi_david(A, B): matrix, positions = {}, {} result = min_multi_helper(A, B, len(B) - 1, len(B) - len(A), matrix, positions) #print positions return result def min_multi_lobatt(a, b): if len(a) < len(b): return 0, [] zeros = len(a) - len(b) m = [] for i in range(0, (len(b)+1)): m.append([0] * (zeros + 1)) import copy r = copy.deepcopy(m) m[0][0] = 0 for i in range(1, len(b) + 1): m[i][0] = m[i - 1][0] + a[i - 1] * b[i - 1] for i in range(1, len(b) + 1): for j in range(1, zeros + 1): r[i][j] = m[i][j - 1] < a[i + j - 1] * b[i - 1] + m[i -1][j] and r[i][j - 1] + 1 or 0 m[i][j] = min(m[i][j - 1], a[i + j - 1] * b[i -1] + m[i -1][j]) #print_matrix(r) #print_matrix(m) i = len(b) j = zeros result = [] while i > 0: if r[i][j] > 0: result.extend([0] * r[i][j]) j -= r[i][j] else: result.append(b[i - 1]) i -= 1 result.extend([0] * (len(a) - len(result))) return m[len(b)][zeros], result[::-1] if __name__ == '__main__': from utils import * for i in range(0, 10): A = random_arr(4, -2, 5) B = random_arr(8, -1, 6) david = min_multi_david(A, B) lobatt, dummy = min_multi_lobatt(B, A) if david != lobatt: print A print B print david print lobatt else: print A print B print "PASS" print ""
[ [ 8, 0, 0.0872, 0.0698, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 1, 0, 0.1279, 0.0116, 0, 0.66, 0.1429, 688, 0, 4, 0, 0, 688, 0, 0 ], [ 1, 0, 0.1395, 0.0116, 0, 0.66...
[ "\"\"\"\nGiven 2 arrays A,B, where x(A.length) < y(B.length), we want to\ninsert (y - x) 0's to A at various places such that A*B is minimum. For instance, if A = (1, -1) and\nB = (1,2, 3, 4), then inserting two 0's in the middle of A such that A = (1, 0, 0, -1) would minimize\nA*B. I think he was looking for a dyn...
#!/usr/bin/env python # -*- indent-tabs-mode: nil; tab-width: 4; coding: utf-8 -*- # vi: set ts=4 sts=4 sw=4 set smarttab set expandtab #http://www.careercup.com/question?id=14991189 #Google interview question """ Design an algorithm that, given a list of n elements in an array, finds all the elements that appear more than n/3 times in the list. The algorithm should run in linear time. (n >=0 ) You are expected to use comparisons and achieve linear time. No hashing/excessive space/ and don't use standard linear time deterministic selection algo """ from collections import defaultdict def find_elements(arr): counter = defaultdict(int) for i in arr: counter[i] += 1 if len(counter) < 3: continue for k in counter.keys(): if counter[k] == 1: del counter[k] else: counter[k] -= 1 for k in counter.iterkeys(): counter[k] = 0 for i in arr: if i in counter: counter[i] += 1 result = [] for k, count in counter.iteritems(): if count > len(arr) / 3: result.append(k) return result from utils import * arr = random_arr(16, 0, 4) print arr print find_elements(arr)
[ [ 8, 0, 0.2414, 0.1034, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 1, 0, 0.3103, 0.0345, 0, 0.66, 0.1667, 193, 0, 1, 0, 0, 193, 0, 0 ], [ 2, 0, 0.5862, 0.5172, 0, 0.66...
[ "\"\"\"\nDesign an algorithm that, given a list of n elements in an array, finds all the elements that appear more than n/3 times in the list. The algorithm should run in linear time. (n >=0 ) You are expected to use comparisons and achieve linear time. No hashing/excessive space/ and don't use standard linear time...
#!/usr/bin/env python # -*- indent-tabs-mode: nil; tab-width: 4; coding: utf-8 -*- # vi: set ts=4 sts=4 sw=4 set smarttab set expandtab #http://www.careercup.com/question?id=9820788 #Facebook interview question """ there is a pyramid with 1 cup at level , 2 at level 2 , 3 at level 3 and so on.. It looks something like this 1 2 3 4 5 6 every cup has capacity C. you pour L liters of water from top . when cup 1 gets filled , it overflows to cup 2,3 equally, and when they get filled , Cup 4 and 6 get water only from 2 and 3 resp but 5 gets water from both the cups and so on. Now given C and M .Find the amount of water in ith cup. """ from utils import * def get_water_amount(capacities, M): capacities = [float(c) for c in capacities] n = len(capacities) level = 2 amounts = [M] for i in range(2, n + 1): #first node if i == level * (level - 1) / 2 + 1: amount = max(0, amounts[i - level] - capacities[i - level]) / 2 #last node elif i == level * (level + 1) / 2: amount = max(0, amounts[i - level - 1] - capacities[i - level - 1]) / 2 level += 1 else: #other nodes amount = max(0, amounts[i - level] - capacities[i - level]) / 2 + max(0, amounts[i - level - 1] - capacities[i - level - 1]) / 2 amounts.append(amount) for i in range(0, n): amounts[i] = min(amounts[i], capacities[i]) return amounts if __name__ == '__main__': capacities = random_arr(15, 10, 30) amounts = get_water_amount(capacities, 100) print capacities, 100 print amounts
[ [ 8, 0, 0.2326, 0.2093, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 1, 0, 0.3488, 0.0233, 0, 0.66, 0.3333, 970, 0, 1, 0, 0, 970, 0, 0 ], [ 2, 0, 0.6047, 0.4419, 0, 0.66...
[ "\"\"\"\nthere is a pyramid with 1 cup at level , 2 at level 2 , 3 at level 3 and so on..\nIt looks something like this \n1\n2 3\n4 5 6\nevery cup has capacity C. you pour L liters of water from top . when cup 1 gets filled , it overflows to cup 2,3 equally, and when they get filled , Cup 4 and 6 get water only fro...
#!/usr/bin/env python # -*- indent-tabs-mode: nil; tab-width: 4; coding: utf-8 -*- # vi: set ts=4 sts=4 sw=4 set smarttab set expandtab #http://www.careercup.com/question?id=9332640 #Facebook interview question """ Really like the linear solution of this problem. You have an array of 0s and 1s and you want to output all the intervals (i, j) where the number of 0s and numbers of 1s are equal. Example pos = 0 1 2 3 4 5 6 7 8 0 1 0 0 1 1 1 1 0 One interval is (0, 1) because there the number of 0 and 1 are equal. There are many other intervals, find all of them in linear time. """ from collections import defaultdict def get_equal_intervals(arr): sums = defaultdict(list) sums[0.5].append(-1) sum_value = 0 result = [] for i in range(0, len(arr)): sum_value += arr[i] temp = sum_value - float(i) / 2 if temp in sums: for interval_start in sums[temp]: result.append((interval_start + 1, i)) sums[temp].append(i) return result if __name__ == '__main__': from utils import * arr = random_arr(10, 0, 1) print arr print get_equal_intervals(arr)
[ [ 8, 0, 0.3, 0.2857, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 1, 0, 0.4571, 0.0286, 0, 0.66, 0.3333, 193, 0, 1, 0, 0, 193, 0, 0 ], [ 2, 0, 0.6571, 0.3714, 0, 0.66, ...
[ "\"\"\"\nReally like the linear solution of this problem. You have an array of 0s and 1s and you want to output all the intervals (i, j) where the number of 0s and numbers of 1s are equal.\n\nExample\n\npos = 0 1 2 3 4 5 6 7 8\n0 1 0 0 1 1 1 1 0", "from collections import defaultdict", "def get_equal_intervals(...
#!/usr/bin/env python # -*- indent-tabs-mode: nil; tab-width: 4; coding: utf-8 -*- # vi: set ts=4 sts=4 sw=4 set smarttab set expandtab """ http://www.careercup.com/question?id=14967793 You are given an input form such as the following (1, (2, 3), (4, (5, 6), 7)) Each element is either a number or a list (whose elements may also be numbers or other lists). Output the numbers as they appear, stripped down into a single list. E.G. (1, 2, 3, 4, 5, 6, 7) (Complication - how does your code handle the case of ((((5)))) vs just ( 5 ) ? ) """ import os, re, sys, getopt import logging import locale def flatten(l, out): """docstring for flatten""" for i in l: if type(i) == tuple: flatten(i, out) else: out.append(i) if __name__ == '__main__': arr = (1, (2, 3), (4, (5, 6), 7)) out = [] flatten(arr, out) print out
[ [ 8, 0, 0.2833, 0.3333, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 1, 0, 0.4667, 0.0333, 0, 0.66, 0.2, 688, 0, 4, 0, 0, 688, 0, 0 ], [ 1, 0, 0.5, 0.0333, 0, 0.66, ...
[ "\"\"\"\nhttp://www.careercup.com/question?id=14967793\nYou are given an input form such as the following\n(1, (2, 3), (4, (5, 6), 7))\nEach element is either a number or a list (whose elements may also be numbers or other lists).\nOutput the numbers as they appear, stripped down into a single list.\nE.G. (1, 2, 3,...
#!/usr/bin/env python # -*- indent-tabs-mode: nil; tab-width: 4; coding: utf-8 -*- # vi: set ts=4 sts=4 sw=4 set smarttab set expandtab #http://www.careercup.com/question?id=12945663 #Facebook interview question """ Write a function f(n) which computes the number of scoring sequences that add up to score n. """ def calculate(num, scores, start_index): result = 0 score = scores[start_index] if start_index == len(scores) - 1: return num % score == 0 for i in range(0, num / score + 1): result += calculate(num - score * i, scores, start_index + 1) return result scores = [3, 5, 7] print calculate(21, scores, 0)
[ [ 8, 0, 0.35, 0.15, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 2, 0, 0.675, 0.4, 0, 0.66, 0.3333, 85, 0, 3, 1, 0, 0, 0, 3 ], [ 14, 1, 0.55, 0.05, 1, 0.3, 0, 51...
[ "\"\"\"\nWrite a function f(n) which computes the number of scoring sequences that add up to score n.\n\"\"\"", "def calculate(num, scores, start_index):\n result = 0\n score = scores[start_index]\n if start_index == len(scores) - 1:\n return num % score == 0\n for i in range(0, num / score + 1...
#!/usr/bin/env python # -*- indent-tabs-mode: nil; tab-width: 4; coding: utf-8 -*- # vi: set ts=4 sts=4 sw=4 set smarttab set expandtab #http://www.careercup.com/question?id=14633700 #Facebook interview question """ Determine winner of 2/9 number game Two players play the following game: they pick a random number N (less than 2 billion) then, starting from 1, take turns multiplying the number from the previous turn with either 2 or 9 (their choice). Whoever reaches N first wins. The candidate should write a function that given N decides who wins (first or second player)? """ def get_winner(n, buf): if n <= 9: return 1 if n in buf: return buf[n] result = 2 if get_winner((n + 8) / 9, buf) == 2: result = 1 elif get_winner((n + 1) / 2, buf) == 2: result = 1 buf[n] = result return result buf = {} [get_winner(i, buf) for i in range(100, 1000)] print buf
[ [ 8, 0, 0.3393, 0.2857, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 2, 0, 0.6607, 0.2857, 0, 0.66, 0.25, 214, 0, 2, 1, 0, 0, 0, 2 ], [ 4, 1, 0.5714, 0.0357, 1, 0.59, ...
[ "\"\"\"\nDetermine winner of 2/9 number game\n\nTwo players play the following game: they pick a random number N (less than 2 billion) then, \nstarting from 1, take turns multiplying the number from the previous turn with either 2 or 9 (their choice). \nWhoever reaches N first wins. \nThe candidate should write a f...
#!/usr/bin/env python # -*- indent-tabs-mode: nil; tab-width: 4; coding: utf-8 -*- # vi: set ts=4 sts=4 sw=4 set smarttab set expandtab #http://www.careercup.com/question?id=14851686 #Facebook interview question import random def find_point_intersect_most(arr): points = [(interval[0], 0) for interval in arr] + [(interval[1], 1) for interval in arr] points.sort(key = lambda x: x[0]) max_occu, occu, position = 0, 0, -1 for point in points: if point[1]: occu -= 1 else: occu += 1 if occu > max_occu: max_occu = occu position = point[0] return max_occu, position if __name__ == '__main__': for i in range(0, 20): length = random.randint(10, 20) arr = [] for j in range(0, length): start_interval = random.randint(0, 100) end_interval = random.randint(0, 100) + start_interval arr.append((start_interval, end_interval)) print arr, find_point_intersect_most(arr)
[ [ 1, 0, 0.2069, 0.0345, 0, 0.66, 0, 715, 0, 1, 0, 0, 715, 0, 0 ], [ 2, 0, 0.4828, 0.3793, 0, 0.66, 0.5, 462, 0, 1, 1, 0, 0, 0, 1 ], [ 14, 1, 0.3448, 0.0345, 1, 0.5,...
[ "import random", "def find_point_intersect_most(arr):\n points = [(interval[0], 0) for interval in arr] + [(interval[1], 1) for interval in arr]\n points.sort(key = lambda x: x[0])\n max_occu, occu, position = 0, 0, -1\n for point in points:\n if point[1]: occu -= 1\n else: occu += 1\n ...
#!/usr/bin/env python # -*- indent-tabs-mode: nil; tab-width: 4; coding: utf-8 -*- # vi: set ts=4 sts=4 sw=4 set smarttab set expandtab #http://www.careercup.com/question?id=14681714 #Facebook interview question """ Given a set {1,2,3,4,5...n} of n elements, write code that outputs all subsets of length k. For example, if n = 4 and k = 2, the output would be {1, 2}, {1, 3}, {1, 4}, {2, 3}, {2, 4}, {3, 4} """ def preint_subsets(n, k): arr = [i for i in range(1, n + 1)] existing = [] print_sets(arr, existing, 0, k) def print_sets(arr, existing, start_index, k): if k == 0: print existing return if start_index >= len(arr): return for i in range(start_index, len(arr)): existing.append(arr[i]) print_sets(arr, existing, i + 1, k - 1) existing.pop() preint_subsets(6, 4)
[ [ 8, 0, 0.2414, 0.1034, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 2, 0, 0.3966, 0.1379, 0, 0.66, 0.3333, 105, 0, 2, 0, 0, 0, 0, 2 ], [ 14, 1, 0.3793, 0.0345, 1, 0.55,...
[ "\"\"\"\nGiven a set {1,2,3,4,5...n} of n elements, write code that outputs all subsets of length k. For example, if n = 4 and k = 2, the output would be {1, 2}, {1, 3}, {1, 4}, {2, 3}, {2, 4}, {3, 4}\n\"\"\"", "def preint_subsets(n, k):\n arr = [i for i in range(1, n + 1)]\n existing = []\n print_sets(a...
#!/usr/bin/env python # -*- indent-tabs-mode: nil; tab-width: 4; coding: utf-8 -*- # vi: set ts=4 sts=4 sw=4 set smarttab set expandtab #http://www.careercup.com/question?id=9332640 #Facebook interview question """ Really like the linear solution of this problem. You have an array of 0s and 1s and you want to output all the intervals (i, j) where the number of 0s and numbers of 1s are equal. Example pos = 0 1 2 3 4 5 6 7 8 0 1 0 0 1 1 1 1 0 One interval is (0, 1) because there the number of 0 and 1 are equal. There are many other intervals, find all of them in linear time. """ from collections import defaultdict def get_equal_intervals(arr): sums = defaultdict(list) sums[0.5].append(-1) sum_value = 0 result = [] for i in range(0, len(arr)): sum_value += arr[i] temp = sum_value - float(i) / 2 if temp in sums: for interval_start in sums[temp]: result.append((interval_start + 1, i)) sums[temp].append(i) return result if __name__ == '__main__': from utils import * arr = random_arr(10, 0, 1) print arr print get_equal_intervals(arr)
[ [ 8, 0, 0.3, 0.2857, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 1, 0, 0.4571, 0.0286, 0, 0.66, 0.3333, 193, 0, 1, 0, 0, 193, 0, 0 ], [ 2, 0, 0.6571, 0.3714, 0, 0.66, ...
[ "\"\"\"\nReally like the linear solution of this problem. You have an array of 0s and 1s and you want to output all the intervals (i, j) where the number of 0s and numbers of 1s are equal.\n\nExample\n\npos = 0 1 2 3 4 5 6 7 8\n0 1 0 0 1 1 1 1 0", "from collections import defaultdict", "def get_equal_intervals(...
#!/usr/bin/env python # -*- indent-tabs-mode: nil; tab-width: 4; coding: utf-8 -*- # vi: set ts=4 sts=4 sw=4 set smarttab set expandtab #http://www.careercup.com/question?id=14851686 #Facebook interview question from utils import * def find_non_adjacent_sub_sequence(arr): if not arr: return (0, ) if len(arr) == 1: return (1, arr[0]) last_index, max_sum, max_sum_sequence = [], 0, [] max_sum_index = -1 for i in range(0, len(arr)): if i <= 1: last_index.append(-1) max_sum_sequence.append(arr[i]) elif i == 2: last_index.append(0) max_sum_sequence.append(arr[i] + arr[0]) else: if max_sum_sequence[i - 2] > max_sum_sequence[i - 3]: last_index.append(i - 2) max_sum_sequence.append(arr[i] + max_sum_sequence[i - 2]) else: last_index.append(i - 3) max_sum_sequence.append(arr[i] + max_sum_sequence[i - 3]) if max_sum_sequence[i] > max_sum: max_sum, max_sum_index = max_sum_sequence[i], i return max_sum, find_sub_sequence(arr, last_index, max_sum_index) def find_sub_sequence(arr, last_index, index): result = [] while index != -1: result.append(index) index = last_index[index] result.reverse() return result if __name__ == "__main__": for i in range(0, 20): arr = random_arr() print find_non_adjacent_sub_sequence(arr)
[ [ 1, 0, 0.1489, 0.0213, 0, 0.66, 0, 970, 0, 1, 0, 0, 970, 0, 0 ], [ 2, 0, 0.4362, 0.5106, 0, 0.66, 0.3333, 326, 0, 1, 1, 0, 0, 0, 12 ], [ 4, 1, 0.2128, 0.0213, 1, 0...
[ "from utils import *", "def find_non_adjacent_sub_sequence(arr):\n if not arr: return (0, )\n if len(arr) == 1: return (1, arr[0])\n last_index, max_sum, max_sum_sequence = [], 0, []\n max_sum_index = -1\n\n for i in range(0, len(arr)):\n if i <= 1:", " if not arr: return (0, )", " ...
#!/usr/bin/env python # -*- indent-tabs-mode: nil; tab-width: 4; coding: utf-8 -*- # vi: set ts=4 sts=4 sw=4 set smarttab set expandtab #http://www.careercup.com/question?id=12945663 #Facebook interview question """ Write a function f(n) which computes the number of scoring sequences that add up to score n. """ def calculate(num, scores, start_index): result = 0 score = scores[start_index] if start_index == len(scores) - 1: return num % score == 0 for i in range(0, num / score + 1): result += calculate(num - score * i, scores, start_index + 1) return result scores = [3, 5, 7] print calculate(21, scores, 0)
[ [ 8, 0, 0.35, 0.15, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 2, 0, 0.675, 0.4, 0, 0.66, 0.3333, 85, 0, 3, 1, 0, 0, 0, 3 ], [ 14, 1, 0.55, 0.05, 1, 0.21, 0, 5...
[ "\"\"\"\nWrite a function f(n) which computes the number of scoring sequences that add up to score n.\n\"\"\"", "def calculate(num, scores, start_index):\n result = 0\n score = scores[start_index]\n if start_index == len(scores) - 1:\n return num % score == 0\n for i in range(0, num / score + 1...
#!/usr/bin/env python # -*- indent-tabs-mode: nil; tab-width: 4; coding: utf-8 -*- # vi: set ts=4 sts=4 sw=4 set smarttab set expandtab #http://www.careercup.com/question?id=14851686 #Facebook interview question import random import time def random_arr(length = random.randint(10, 20), min = 0, max = 100): result = [random.randint(min, max) for i in range(length)] return result def random_str(length = random.randint(10, 20), chars = None): a, A = ord('a'), ord('A') if not chars: chars = [chr(i + a) for i in range(26)] + [chr(i + A) for i in range(26)] candidates_length = len(chars) result = [chars[random.randint(0, candidates_length - 1)] for i in range(length)] return "".join(result) def arr_to_str(arr): return "".join([chr(i + ord('a')) for i in arr]) def print_pass(): print '\x1b[32m PASS \x1b[0m' def print_fail(): print '\x1b[31m FAIL \x1b[0m' def time_profile(func): def timing_and_call(*args, **kwargs): start_time = time.time() try: return func(*args, **kwargs) finally: print func.__name__, ' running time: ', (time.time() - start_time) * 1000 , ' ms' return timing_and_call def check_result(david, lobatt, args): david = david(*args) lobatt = lobatt(*args) if david != lobatt: print_fail() print "david", david print "lobatt", lobatt else: print_pass()
[ [ 1, 0, 0.1458, 0.0208, 0, 0.66, 0, 715, 0, 1, 0, 0, 715, 0, 0 ], [ 1, 0, 0.1667, 0.0208, 0, 0.66, 0.125, 654, 0, 1, 0, 0, 654, 0, 0 ], [ 2, 0, 0.2292, 0.0625, 0, 0...
[ "import random", "import time", "def random_arr(length = random.randint(10, 20), min = 0, max = 100):\n result = [random.randint(min, max) for i in range(length)]\n return result", " result = [random.randint(min, max) for i in range(length)]", " return result", "def random_str(length = random....
#!/usr/bin/env python # -*- indent-tabs-mode: nil; tab-width: 4; coding: utf-8 -*- # vi: set ts=4 sts=4 sw=4 set smarttab set expandtab #http://www.careercup.com/question?id=14633700 #Facebook interview question """ Determine winner of 2/9 number game Two players play the following game: they pick a random number N (less than 2 billion) then, starting from 1, take turns multiplying the number from the previous turn with either 2 or 9 (their choice). Whoever reaches N first wins. The candidate should write a function that given N decides who wins (first or second player)? """ def get_winner(n, buf): if n <= 9: return 1 if n in buf: return buf[n] result = 2 if get_winner((n + 8) / 9, buf) == 2: result = 1 elif get_winner((n + 1) / 2, buf) == 2: result = 1 buf[n] = result return result buf = {} [get_winner(i, buf) for i in range(100, 1000)] print buf
[ [ 8, 0, 0.3393, 0.2857, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 2, 0, 0.6607, 0.2857, 0, 0.66, 0.25, 214, 0, 2, 1, 0, 0, 0, 2 ], [ 4, 1, 0.5714, 0.0357, 1, 0.64, ...
[ "\"\"\"\nDetermine winner of 2/9 number game\n\nTwo players play the following game: they pick a random number N (less than 2 billion) then, \nstarting from 1, take turns multiplying the number from the previous turn with either 2 or 9 (their choice). \nWhoever reaches N first wins. \nThe candidate should write a f...
#!/usr/bin/env python # -*- indent-tabs-mode: nil; tab-width: 4; coding: utf-8 -*- # vi: set ts=4 sts=4 sw=4 set smarttab set expandtab #http://www.careercup.com/question?id=14945498 #Google interview question import os, re, sys, getopt import logging import locale if __name__ == '__main__': output = [] buf = [] while True: cur = sys.stdin.readline().rstrip('\n') #end exit if cur == '$$': sys.exit(0) #number stream ends if cur == '$': if len(buf) > 0: if buf[-1] == 9: output.append(buf[0] + 1) if len(buf) > 1: output.extend([0] * (len(buf) - 1)) else: buf[-1] = buf[-1] + 1; output.extend(buf) print output output = [] buf = [] #if there is a <9, then put all previous number into output elif int(cur) < 9: if len(buf) > 0: output.extend(buf) buf = [] buf.append(int(cur)) #if there is a 9, then put into buf elif int(cur) == 9: buf.append(int(cur)) else: print "Ignoring char %s"%cur
[ [ 1, 0, 0.1429, 0.0238, 0, 0.66, 0, 688, 0, 4, 0, 0, 688, 0, 0 ], [ 1, 0, 0.1667, 0.0238, 0, 0.66, 0.3333, 715, 0, 1, 0, 0, 715, 0, 0 ], [ 1, 0, 0.1905, 0.0238, 0, ...
[ "import os, re, sys, getopt", "import logging", "import locale", "if __name__ == '__main__':\n output = []\n buf = []\n while True:\n cur = sys.stdin.readline().rstrip('\\n')\n #end exit\n if cur == '$$':\n sys.exit(0)", " output = []", " buf = []", " wh...
#!/usr/bin/env python # -*- indent-tabs-mode: nil; tab-width: 4; coding: utf-8 -*- # vi: set ts=4 sts=4 sw=4 set smarttab set expandtab #http://www.careercup.com/question?id=9820788 #Facebook interview question """ there is a pyramid with 1 cup at level , 2 at level 2 , 3 at level 3 and so on.. It looks something like this 1 2 3 4 5 6 every cup has capacity C. you pour L liters of water from top . when cup 1 gets filled , it overflows to cup 2,3 equally, and when they get filled , Cup 4 and 6 get water only from 2 and 3 resp but 5 gets water from both the cups and so on. Now given C and M .Find the amount of water in ith cup. """ from utils import * def get_water_amount(capacities, M): capacities = [float(c) for c in capacities] n = len(capacities) level = 2 amounts = [M] for i in range(2, n + 1): #first node if i == level * (level - 1) / 2 + 1: amount = max(0, amounts[i - level] - capacities[i - level]) / 2 #last node elif i == level * (level + 1) / 2: amount = max(0, amounts[i - level - 1] - capacities[i - level - 1]) / 2 level += 1 else: #other nodes amount = max(0, amounts[i - level] - capacities[i - level]) / 2 + max(0, amounts[i - level - 1] - capacities[i - level - 1]) / 2 amounts.append(amount) for i in range(0, n): amounts[i] = min(amounts[i], capacities[i]) return amounts if __name__ == '__main__': capacities = random_arr(15, 10, 30) amounts = get_water_amount(capacities, 100) print capacities, 100 print amounts
[ [ 8, 0, 0.2326, 0.2093, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 1, 0, 0.3488, 0.0233, 0, 0.66, 0.3333, 970, 0, 1, 0, 0, 970, 0, 0 ], [ 2, 0, 0.6047, 0.4419, 0, 0.66...
[ "\"\"\"\nthere is a pyramid with 1 cup at level , 2 at level 2 , 3 at level 3 and so on..\nIt looks something like this \n1\n2 3\n4 5 6\nevery cup has capacity C. you pour L liters of water from top . when cup 1 gets filled , it overflows to cup 2,3 equally, and when they get filled , Cup 4 and 6 get water only fro...
#!/usr/bin/env python # -*- indent-tabs-mode: nil; tab-width: 4; coding: utf-8 -*- # vi: set ts=4 sts=4 sw=4 set smarttab set expandtab """ http://www.careercup.com/question?id=14967793 You are given an input form such as the following (1, (2, 3), (4, (5, 6), 7)) Each element is either a number or a list (whose elements may also be numbers or other lists). Output the numbers as they appear, stripped down into a single list. E.G. (1, 2, 3, 4, 5, 6, 7) (Complication - how does your code handle the case of ((((5)))) vs just ( 5 ) ? ) """ import os, re, sys, getopt import logging import locale def flatten(l, out): """docstring for flatten""" for i in l: if type(i) == tuple: flatten(i, out) else: out.append(i) if __name__ == '__main__': arr = (1, (2, 3), (4, (5, 6), 7)) out = [] flatten(arr, out) print out
[ [ 8, 0, 0.2833, 0.3333, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 1, 0, 0.4667, 0.0333, 0, 0.66, 0.2, 688, 0, 4, 0, 0, 688, 0, 0 ], [ 1, 0, 0.5, 0.0333, 0, 0.66, ...
[ "\"\"\"\nhttp://www.careercup.com/question?id=14967793\nYou are given an input form such as the following\n(1, (2, 3), (4, (5, 6), 7))\nEach element is either a number or a list (whose elements may also be numbers or other lists).\nOutput the numbers as they appear, stripped down into a single list.\nE.G. (1, 2, 3,...
#!/usr/bin/env python # -*- indent-tabs-mode: nil; tab-width: 4; coding: utf-8 -*- # vi: set ts=4 sts=4 sw=4 set smarttab set expandtab #http://www.careercup.com/question?id=13216725 #Facebook interview question """ An expression consisting of operands and binary operators can be written in Reverse Polish Notation (RPN) by writing both the operands followed by the operator. For example, 3 + (4 * 5) can be written as "3 4 5 * +". You are given a string consisting of x's and *'s. x represents an operand and * represents a binary operator. It is easy to see that not all such strings represent valid RPN expressions. For example, the "x*x" is not a valid RPN expression, while "xx*" and "xxx**" are valid expressions. What is the minimum number of insert, delete and replace operations needed to convert the given string into a valid RPN expression? Input: The first line contains the number of test cases T. T test cases follow. Each case contains a string consisting only of characters x and *. Output: Output T lines, one for each test case containing the least number of operations needed. Constraints: 1 <= T <= 100 The length of the input string will be at most 100. Sample Input: 5 x xx* xxx** *xx xx*xx** Sample Output: 0 0 0 2 0 Explanation: For the first three cases, the input expression is already a valid RPN, so the answer is 0. For the fourth case, we can perform one delete, and one insert operation: xx -> xx -> xx """ from collections import defaultdict def get_operation_count(expression, index): result = defaultdict(lambda: 10000) if index < 0: return result c = expression[index] items = get_operation_count(expression, index - 1) if not items: items[0] = 0 for operand_count, change_count in items.iteritems(): if c == 'x': result[operand_count + 1] = change_count else: if operand_count > 1: result[operand_count - 1] = change_count elif operand_count == 1: result[1] = min(result[1], change_count + 1) result[2] = min(result[2], change_count + 1) else: result[0] = min(result[0], change_count + 1) result[1] = min(result[1], change_count + 1) return result def calculate_min_change_count(expression): items = get_operation_count(expression, len(expression) - 1) result = 10000 for operand_count, change_count in items.iteritems(): result = min(operand_count / 2 + change_count, result) return result def convert_str(arr): result = [] for i in arr: result.append(i == 0 and "x" or "*") return "".join(result) from utils import * for i in range(0, 10): arr = random_arr(10, 0, 1) expression = convert_str(arr) print expression, calculate_min_change_count(expression)
[ [ 8, 0, 0.277, 0.4054, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 1, 0, 0.4865, 0.0135, 0, 0.66, 0.1667, 193, 0, 1, 0, 0, 193, 0, 0 ], [ 2, 0, 0.6149, 0.2432, 0, 0.66,...
[ "\"\"\"\nAn expression consisting of operands and binary operators can be written in Reverse Polish Notation (RPN) by writing both the operands followed by the operator. For example, 3 + (4 * 5) can be written as \"3 4 5 * +\".\n\nYou are given a string consisting of x's and *'s. x represents an operand and * repre...
#!/usr/bin/env python # -*- indent-tabs-mode: nil; tab-width: 4; coding: utf-8 -*- # vi: set ts=4 sts=4 sw=4 set smarttab set expandtab #http://www.careercup.com/question?id=14945498 #Google interview question import os, re, sys, getopt import logging import locale if __name__ == '__main__': output = [] buf = [] while True: cur = sys.stdin.readline().rstrip('\n') #end exit if cur == '$$': sys.exit(0) #number stream ends if cur == '$': if len(buf) > 0: if buf[-1] == 9: output.append(buf[0] + 1) if len(buf) > 1: output.extend([0] * (len(buf) - 1)) else: buf[-1] = buf[-1] + 1; output.extend(buf) print output output = [] buf = [] #if there is a <9, then put all previous number into output elif int(cur) < 9: if len(buf) > 0: output.extend(buf) buf = [] buf.append(int(cur)) #if there is a 9, then put into buf elif int(cur) == 9: buf.append(int(cur)) else: print "Ignoring char %s"%cur
[ [ 1, 0, 0.1429, 0.0238, 0, 0.66, 0, 688, 0, 4, 0, 0, 688, 0, 0 ], [ 1, 0, 0.1667, 0.0238, 0, 0.66, 0.3333, 715, 0, 1, 0, 0, 715, 0, 0 ], [ 1, 0, 0.1905, 0.0238, 0, ...
[ "import os, re, sys, getopt", "import logging", "import locale", "if __name__ == '__main__':\n output = []\n buf = []\n while True:\n cur = sys.stdin.readline().rstrip('\\n')\n #end exit\n if cur == '$$':\n sys.exit(0)", " output = []", " buf = []", " wh...
#!/usr/bin/env python # -*- indent-tabs-mode: nil; tab-width: 4; coding: utf-8 -*- # vi: set ts=4 sts=4 sw=4 set smarttab set expandtab #http://www.careercup.com/question?id=14851686 #Facebook interview question import random import time def random_arr(length = random.randint(10, 20), min = 0, max = 100): result = [random.randint(min, max) for i in range(length)] return result def random_str(length = random.randint(10, 20), chars = None): a, A = ord('a'), ord('A') if not chars: chars = [chr(i + a) for i in range(26)] + [chr(i + A) for i in range(26)] candidates_length = len(chars) result = [chars[random.randint(0, candidates_length - 1)] for i in range(length)] return "".join(result) def arr_to_str(arr): return "".join([chr(i + ord('a')) for i in arr]) def print_pass(): print '\x1b[32m PASS \x1b[0m' def print_fail(): print '\x1b[31m FAIL \x1b[0m' def time_profile(func): def timing_and_call(*args, **kwargs): start_time = time.time() try: return func(*args, **kwargs) finally: print func.__name__, ' running time: ', (time.time() - start_time) * 1000 , ' ms' return timing_and_call def check_result(david, lobatt, args): david = david(*args) lobatt = lobatt(*args) if david != lobatt: print_fail() print "david", david print "lobatt", lobatt else: print_pass()
[ [ 1, 0, 0.1458, 0.0208, 0, 0.66, 0, 715, 0, 1, 0, 0, 715, 0, 0 ], [ 1, 0, 0.1667, 0.0208, 0, 0.66, 0.125, 654, 0, 1, 0, 0, 654, 0, 0 ], [ 2, 0, 0.2292, 0.0625, 0, 0...
[ "import random", "import time", "def random_arr(length = random.randint(10, 20), min = 0, max = 100):\n result = [random.randint(min, max) for i in range(length)]\n return result", " result = [random.randint(min, max) for i in range(length)]", " return result", "def random_str(length = random....
#!/usr/bin/env python # -*- indent-tabs-mode: nil; tab-width: 4; coding: utf-8 -*- # vi: set ts=4 sts=4 sw=4 set smarttab set expandtab #http://www.careercup.com/question?id=14681714 #Facebook interview question """ Given a set {1,2,3,4,5...n} of n elements, write code that outputs all subsets of length k. For example, if n = 4 and k = 2, the output would be {1, 2}, {1, 3}, {1, 4}, {2, 3}, {2, 4}, {3, 4} """ def preint_subsets(n, k): arr = [i for i in range(1, n + 1)] existing = [] print_sets(arr, existing, 0, k) def print_sets(arr, existing, start_index, k): if k == 0: print existing return if start_index >= len(arr): return for i in range(start_index, len(arr)): existing.append(arr[i]) print_sets(arr, existing, i + 1, k - 1) existing.pop() preint_subsets(6, 4)
[ [ 8, 0, 0.2414, 0.1034, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 2, 0, 0.3966, 0.1379, 0, 0.66, 0.3333, 105, 0, 2, 0, 0, 0, 0, 2 ], [ 14, 1, 0.3793, 0.0345, 1, 0.15,...
[ "\"\"\"\nGiven a set {1,2,3,4,5...n} of n elements, write code that outputs all subsets of length k. For example, if n = 4 and k = 2, the output would be {1, 2}, {1, 3}, {1, 4}, {2, 3}, {2, 4}, {3, 4}\n\"\"\"", "def preint_subsets(n, k):\n arr = [i for i in range(1, n + 1)]\n existing = []\n print_sets(a...
#!/usr/bin/env python # -*- indent-tabs-mode: nil; tab-width: 4; coding: utf-8 -*- # vi: set ts=4 sts=4 sw=4 set smarttab set expandtab #http://www.careercup.com/question?id=14851686 #Facebook interview question import random def find_point_intersect_most(arr): points = [(interval[0], 0) for interval in arr] + [(interval[1], 1) for interval in arr] points.sort(key = lambda x: x[0]) max_occu, occu, position = 0, 0, -1 for point in points: if point[1]: occu -= 1 else: occu += 1 if occu > max_occu: max_occu = occu position = point[0] return max_occu, position if __name__ == '__main__': for i in range(0, 20): length = random.randint(10, 20) arr = [] for j in range(0, length): start_interval = random.randint(0, 100) end_interval = random.randint(0, 100) + start_interval arr.append((start_interval, end_interval)) print arr, find_point_intersect_most(arr)
[ [ 1, 0, 0.2069, 0.0345, 0, 0.66, 0, 715, 0, 1, 0, 0, 715, 0, 0 ], [ 2, 0, 0.4828, 0.3793, 0, 0.66, 0.5, 462, 0, 1, 1, 0, 0, 0, 1 ], [ 14, 1, 0.3448, 0.0345, 1, 0.82...
[ "import random", "def find_point_intersect_most(arr):\n points = [(interval[0], 0) for interval in arr] + [(interval[1], 1) for interval in arr]\n points.sort(key = lambda x: x[0])\n max_occu, occu, position = 0, 0, -1\n for point in points:\n if point[1]: occu -= 1\n else: occu += 1\n ...
import random """ http://www.careercup.com/question?id=14859694 Given an array and a key, sum min subarray whose sum is no less than key. O(n) Time needed Assumption: all positive intergers in the array """ def minLength(arr, k): min_length, sum, start = len(arr) + 1, 0, 0 s, e = -1, -1 for i in range(0, len(arr)): sum += arr[i] while sum - arr[start] >= k: sum -= arr[start] start += 1 if sum >= k and i - start + 1 < min_length: min_length, s, e = i - start + 1, start, i return min_length, s, e def check(arr, k): min_length, s, e = len(arr) + 1, -1, -1 sum, arr_sum = 0, [0] for item in arr: sum += item arr_sum.append(sum) for i in range(0, len(arr)): for j in range(i + 1, len(arr)): if arr_sum[j] - arr_sum[i] >= k: if j - i < min_length: min_length = j - i s, e = i, j - 1 break return min_length, s, e def findMin(a, k): if len(a) == 0: return (-1,0,0) for i, v in enumerate(a): if v > k: return (1, i, i) minlen = -1 minstart, minend = 0, 0 i, j, sum = 0, 0, a[0] while j < len(a): if sum < k: j += 1 if j < len(a): sum += a[j] else: while sum - a[i] >= k and i < j: sum -= a[i] i += 1 if minlen < 0 or j - i + 1 < minlen: minlen = j - i + 1; minstart = i minend = j if j + 1 < len(a): sum += a[j+1] sum -= a[i] i += 1 j += 1 #print "tempo:" + str(minlen) + " " + str(i) + " " + str(j), #print "sum = " + str(sum) return (minlen, minstart, minend) if __name__ == '__main__': for i in range(0, 20): from utils import * length = random.randint(10, 20) max = random.randint(10, 100) arr = random_arr(length, 1, max / random.randint(2, 5)) min_length = minLength(arr, max) min_l2 = findMin(arr, max) print arr, max, min_length, check(arr, max), min_l2
[ [ 1, 0, 0.0133, 0.0133, 0, 0.66, 0, 715, 0, 1, 0, 0, 715, 0, 0 ], [ 8, 0, 0.0733, 0.08, 0, 0.66, 0.2, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 2, 0, 0.2, 0.1467, 0, 0.66, 0....
[ "import random", "\"\"\"\nhttp://www.careercup.com/question?id=14859694\nGiven an array and a key, sum min subarray whose sum is no less than key. O(n) Time needed\n\nAssumption: all positive intergers in the array\n\"\"\"", "def minLength(arr, k):\n min_length, sum, start = len(arr) + 1, 0, 0\n s, e = -1...
#!/usr/bin/env python # -*- indent-tabs-mode: nil; tab-width: 4; coding: utf-8 -*- # vi: set ts=4 sts=4 sw=4 set smarttab set expandtab #http://www.careercup.com/question?id=13216725 #Facebook interview question """ An expression consisting of operands and binary operators can be written in Reverse Polish Notation (RPN) by writing both the operands followed by the operator. For example, 3 + (4 * 5) can be written as "3 4 5 * +". You are given a string consisting of x's and *'s. x represents an operand and * represents a binary operator. It is easy to see that not all such strings represent valid RPN expressions. For example, the "x*x" is not a valid RPN expression, while "xx*" and "xxx**" are valid expressions. What is the minimum number of insert, delete and replace operations needed to convert the given string into a valid RPN expression? Input: The first line contains the number of test cases T. T test cases follow. Each case contains a string consisting only of characters x and *. Output: Output T lines, one for each test case containing the least number of operations needed. Constraints: 1 <= T <= 100 The length of the input string will be at most 100. Sample Input: 5 x xx* xxx** *xx xx*xx** Sample Output: 0 0 0 2 0 Explanation: For the first three cases, the input expression is already a valid RPN, so the answer is 0. For the fourth case, we can perform one delete, and one insert operation: xx -> xx -> xx """ from collections import defaultdict def get_operation_count(expression, index): result = defaultdict(lambda: 10000) if index < 0: return result c = expression[index] items = get_operation_count(expression, index - 1) if not items: items[0] = 0 for operand_count, change_count in items.iteritems(): if c == 'x': result[operand_count + 1] = change_count else: if operand_count > 1: result[operand_count - 1] = change_count elif operand_count == 1: result[1] = min(result[1], change_count + 1) result[2] = min(result[2], change_count + 1) else: result[0] = min(result[0], change_count + 1) result[1] = min(result[1], change_count + 1) return result def calculate_min_change_count(expression): items = get_operation_count(expression, len(expression) - 1) result = 10000 for operand_count, change_count in items.iteritems(): result = min(operand_count / 2 + change_count, result) return result def convert_str(arr): result = [] for i in arr: result.append(i == 0 and "x" or "*") return "".join(result) from utils import * for i in range(0, 10): arr = random_arr(10, 0, 1) expression = convert_str(arr) print expression, calculate_min_change_count(expression)
[ [ 8, 0, 0.277, 0.4054, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 1, 0, 0.4865, 0.0135, 0, 0.66, 0.1667, 193, 0, 1, 0, 0, 193, 0, 0 ], [ 2, 0, 0.6149, 0.2432, 0, 0.66,...
[ "\"\"\"\nAn expression consisting of operands and binary operators can be written in Reverse Polish Notation (RPN) by writing both the operands followed by the operator. For example, 3 + (4 * 5) can be written as \"3 4 5 * +\".\n\nYou are given a string consisting of x's and *'s. x represents an operand and * repre...
#!/usr/bin/env python # -*- indent-tabs-mode: nil; tab-width: 4; coding: utf-8 -*- # vi: set ts=4 sts=4 sw=4 set smarttab set expandtab #http://www.careercup.com/question?id=14851686 #Facebook interview question from utils import * def find_non_adjacent_sub_sequence(arr): if not arr: return (0, ) if len(arr) == 1: return (1, arr[0]) last_index, max_sum, max_sum_sequence = [], 0, [] max_sum_index = -1 for i in range(0, len(arr)): if i <= 1: last_index.append(-1) max_sum_sequence.append(arr[i]) elif i == 2: last_index.append(0) max_sum_sequence.append(arr[i] + arr[0]) else: if max_sum_sequence[i - 2] > max_sum_sequence[i - 3]: last_index.append(i - 2) max_sum_sequence.append(arr[i] + max_sum_sequence[i - 2]) else: last_index.append(i - 3) max_sum_sequence.append(arr[i] + max_sum_sequence[i - 3]) if max_sum_sequence[i] > max_sum: max_sum, max_sum_index = max_sum_sequence[i], i return max_sum, find_sub_sequence(arr, last_index, max_sum_index) def find_sub_sequence(arr, last_index, index): result = [] while index != -1: result.append(index) index = last_index[index] result.reverse() return result if __name__ == "__main__": for i in range(0, 20): arr = random_arr() print find_non_adjacent_sub_sequence(arr)
[ [ 1, 0, 0.1489, 0.0213, 0, 0.66, 0, 970, 0, 1, 0, 0, 970, 0, 0 ], [ 2, 0, 0.4362, 0.5106, 0, 0.66, 0.3333, 326, 0, 1, 1, 0, 0, 0, 12 ], [ 4, 1, 0.2128, 0.0213, 1, 0...
[ "from utils import *", "def find_non_adjacent_sub_sequence(arr):\n if not arr: return (0, )\n if len(arr) == 1: return (1, arr[0])\n last_index, max_sum, max_sum_sequence = [], 0, []\n max_sum_index = -1\n\n for i in range(0, len(arr)):\n if i <= 1:", " if not arr: return (0, )", " ...
''' Created on Apr 16, 2012 @author: Gangli ''' import argparse; import re; import sys; logcodes = []; def addlogcode(logcode): global logcodes; if logcode not in logcodes: logcodes.append(logcode); def inlogcodelist(logcode): global logcodes; return (logcode in logcodes); def linematches(line): mo = re.search("(\s+\d+\s+)(\d+)(\s+\d+\s+)", line); if mo is None: return True; logcode = int(mo.group(2)); return inlogcodelist(logcode); def extract(fin, fout): for line in fin: if linematches(line): fout.write(line); if __name__ == '__main__': pass
[ [ 8, 0, 0.0833, 0.1389, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 1, 0, 0.1944, 0.0278, 0, 0.66, 0.1111, 325, 0, 1, 0, 0, 325, 0, 0 ], [ 1, 0, 0.2222, 0.0278, 0, 0.66...
[ "'''\nCreated on Apr 16, 2012\n\n@author: Gangli\n'''", "import argparse;", "import re;", "import sys;", "logcodes = [];", "def addlogcode(logcode):\n global logcodes;\n if logcode not in logcodes:\n logcodes.append(logcode);", " if logcode not in logcodes:\n logcodes.append(logco...
import sys; import re; from fnmatch import fnmatch; if __name__ == '__main__': if len(sys.argv) < 2: print "Usage: extractcods.py <javaloader-dir-file>"; sys.exit(1); nCount = 0; with open(sys.argv[1], "rt") as fin: for line in fin: mo = re.search("^(\S+)\s+(\d\.)+\d", line); if mo is None: continue; print "%s.cod" % mo.group(1); nCount += 1; # print "%d files are found." % nCount;
[ [ 1, 0, 0.2, 0.2, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 1, 0, 0.4, 0.2, 0, 0.66, 0.5, 540, 0, 1, 0, 0, 540, 0, 0 ], [ 1, 0, 0.8, 0.2, 0, 0.66, 1, 626,...
[ "import sys;", "import re;", "from fnmatch import fnmatch;" ]
import sys; import os; import os.path; from fnmatch import fnmatch; WHITELIST = ["build.xml" \ , "build-barebone.xml" \ , "build-component.xml" \ , "build-evacuated-component-macros.xml" \ , "build-core.xml" \ , "build-device.xml" \ ]; if __name__ == '__main__': if len(sys.argv) < 2: print "Usage: rmbuildxml.py <directory>"; sys.exit(1); sDirectory = os.path.dirname(sys.argv[1]); for (curdir, dirs, files) in os.walk(sDirectory): for filename in files: if filename.lower() in WHITELIST: continue; if fnmatch(filename, "build-*.xml"): sFileToRemove = os.path.join(curdir, filename); try: os.remove(sFileToRemove); print "{0} is removed.".format(filename); except: print "{0} can not be removed.".format(filename);
[ [ 1, 0, 0.1667, 0.1667, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 1, 0, 0.3333, 0.1667, 0, 0.66, 0.3333, 688, 0, 1, 0, 0, 688, 0, 0 ], [ 1, 0, 0.5, 0.1667, 0, 0.6...
[ "import sys;", "import os;", "import os.path;", "from fnmatch import fnmatch;" ]
import sys; import os; import os.path; from fnmatch import fnmatch; if __name__ == '__main__': if len(sys.argv) < 2: print "Usage: listpng.py <directory>"; sys.exit(1); sDirectory = os.path.dirname(sys.argv[1]); for (curdir, dirs, files) in os.walk(sDirectory): for filename in files: if fnmatch(filename, "*.png"): sFileToList = os.path.join(curdir, filename); # remove leading path sLocalPath = sFileToList[len(sDirectory):]; print sLocalPath;
[ [ 1, 0, 0.1667, 0.1667, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 1, 0, 0.3333, 0.1667, 0, 0.66, 0.3333, 688, 0, 1, 0, 0, 688, 0, 0 ], [ 1, 0, 0.5, 0.1667, 0, 0.6...
[ "import sys;", "import os;", "import os.path;", "from fnmatch import fnmatch;" ]
import numpy as np import numpy.linalg as nl def stripe_length(A): sup = -1 inf = -1 n = A.shape[0] #calcul de la largeur de la bande sup: ballayage des lignes #paralleles a la diagonale en commencant par la plus eloignee #de la diagonale (i.e l'element A(1,n)) for i in np.arange(n): for j in np.arange(i): if (A[j,n+j-i] != 0): #on s'arrete des qu'on recontre sup = n-i #un element non nul et on renvoie break #le nombre de lignes deja parcourues if (sup != -1): break #calcul de la largeur de la bande inf: symetrique a la premiere #etape % a la diagonale for i in np.arange(n): for j in np.arange(i): if (A[n+j-i,j] != 0): inf = n-i break if (inf != -1): break return max(sup, inf) def coef_diag(m): #calcule des elements diagonaux de la matrice m c = np.arange(0,m.shape[0],1) for k in c : c[k] = m[k,k] return c def stripe_inf(m): # calcule la bande inferieure de la matrice m line = np.arange(0,stripe_length(m),1) b = np.zeros([stripe_length(m),m.shape[0]]) column = np.arange(0,m.shape[0]-1,1) for j in column : for i in line : if j+1+i < m.shape[0]: b[i,j] = m[i+1+j,j] return b def stripe_sup(m): # calcule la bande supperieure de la matrice m line = np.arange(0,stripe_length(m),1) e = np.zeros([stripe_length(m),m.shape[0]]) column = np.arange(0,m.shape[0]-1,1) for i in line: for j in column : if j+i+1 < m.shape[0]: e[i,j+i+1] = m[j,j+i+1] return e def goto_full_matrix(b,c,e): # conversion d'une matrice bande vers une matrice pleine m = np.zeros([c.shape[0],c.shape[0]]) line = np.arange(0,b.shape[0],1) column = np.arange(0,c.shape[0],1) if b.shape[0] != e.shape[0]: print "Error dimension" else : #bande supperieure for i in line: for j in column : if j+i+1 < m.shape[0]: m[j,j+i+1] = e[i,j+1+i] #bande inferieure for j in column : for i in line : if j+1+i < m.shape[0]: m[i+1+j,j]= b[i,j] #diagonale for k in column: m[k,k]=c[k] return m # Test print "*************************************" print "*************** TESTS ***************" print "*************************************" m = np.matrix([[1,1,3,0,0],[4,3,-5,2,0],[2,2,5,-3,2],[0,3,2,-1,4],[0,0,1,3,6]]) print "#Matrice m#" print m print "--------------------------" print "stripe_length(m)=",stripe_length(m) print "coef_diag(m)=",coef_diag(m) print "--------------------------" print "stripe_inf(m)=" print stripe_inf(m) print "--------------------------" print "stripe_sup(m)=" print stripe_sup(m) print "--------------------------" print "--------------------------" m1 = np.matrix([[1,1,3,7,0,0],[4,3,-5,2,7,0],[2,2,5,-3,2,6],[1,3,2,-1,4,9],[0,8,1,3,6,3],[0,0,4,5,6,7]]) print "#Matrice m1#" print m1 print "--------------------------" print "stripe_length(m1)=",stripe_length(m1) print "coef_diag(m1)=",coef_diag(m1) print "--------------------------" print "stripe_inf(m1)=" print stripe_inf(m1) print "--------------------------" print "stripe_sup(m1)=" print stripe_sup(m1) print "--------------------------" print "--------------------------" m2 = np.mat('1 0 0 0 0 0 0 ; 2 3 4 1 0 0 0 ; 0 6 8 5 5 6 0 ; 0 5 6 4 8 0 4 ; 0 5 0 1 0 0 0 ; 0 0 1 1 1 1 1 ; 0 0 0 0 1 1 1') print "#Matrice m2#" print m2 print "stripe_length(m2)=",stripe_length(m2) print "coef_diag(m2)=",coef_diag(m2) print "--------------------------" print "stripe_inf(m2)=" print stripe_inf(m2) print "--------------------------" print "stripe_sup(m2)=" print stripe_sup(m2) print "--------------------------" print "--------------------------" print "#TEST GOTO_FULL pour M#" b=np.matrix([[4,2,2,3,0],[2,3,1,0,0]]) c=np.array([1,3,5,-1,6]) e=np.matrix([[0,1,-5,-3,4],[0,0,3,2,2]]) print "b=" print b print "--------------------------" print "c=" print c print "--------------------------" print "e=" print e print "--------------------------" print goto_full_matrix(b,c,e) print "--------------------------" print "--------------------------" print "#TEST GOTO_FULL pour M1#" b1=np.matrix([[4,2,2,3,6,0],[2,3,1,5,0,0],[1,8,4,0,0,0]]) c1=np.array([1,3,5,-1,6,7]) e1=np.matrix([[0,1,-5,-3,4,3],[0,0,3,2,2,9],[0,0,0,7,7,6]]) print "b1=" print b1 print "--------------------------" print "c1=" print c1 print "--------------------------" print "e1=" print e1 print "--------------------------" print goto_full_matrix(b1,c1,e1) print "--------------------------" print "--------------------------" print "#TEST GOTO_FULL pour M2#" b2=np.matrix([[4, 2, 2, 0],[2,3,0,0]]) e2=np.matrix([[0,1,-5,-3],[0,0,3,2]]) c2=np.array([1,3,5,-1]) print "b2=" print b2 print "--------------------------" print "c2=" print c2 print "--------------------------" print "e2=" print e2 print "--------------------------" print goto_full_matrix(b2,c2,e2) def factor_LU(m): #factorisation LU de la matrice m E=stripe_sup(m) B=stripe_inf(m) C=coef_diag(m) d=E.shape[0] n=C.shape[0] L = np.mat(np.arange(n*d).reshape(d,n)) for i in np.arange(n): for k in np.arange(d): L[k,i] = B[k,i]/C[i] B[k,i] = 0 for j in np.arange(k-1,-1,-1): if (i+k<n) : B[j,i+k-j] = B[j,i+k-j] - L[k,i]*E[k-j-1,i+k-j] if (i+k+1 < n) : C[i+k+1] = C[i+k+1] - L[k,i]*E[k,i+k+1] for j in np.arange(d-k-1): if (i+j+k+2 < n) : E[j,i+j+k+2] = E[j,i+j+k+2] - L[k,i]*E[j+k+1,i+j+k+2] return (L,C,E) def LU_solver(A,B): #Resolution du systeme AX=B if (A.shape[0]!=B.shape[0]): print "DIMENTION ERROR" #return -1 else: (L,C,U)=factor_LU(A) n=C.shape[0] d=L.shape[0] X=np.arange(0,n,1.) for i in np.arange(n): X[i]=B[i] for j in np.arange(d): if (i+j>=d): X[i]=X[i]-L[d-j-1,i+j-d]*X[i+j-d] for i in np.arange(n-1,-1,-1): for j in np.arange(d): if ( i+d-j <n): X[i]=X[i]-U[d-j-1,i-j+d]*X[i-j+d] X[i]=X[i]/C[i] return X #test print "--------------------------" print "--------------------------" print "#TEST FACTOR_ALU pour M#" (L,C,U)=factor_LU(m) print L print "-" print C print "-" print U print "---" print "-Solution avec LU_solver : \n" print LU_solver(m,np.arange(0,5,1.)) print "-Solution avec linalg : \n" print np.linalg.solve(m,np.arange(0,5,1.))
[ [ 1, 0, 0.004, 0.004, 0, 0.66, 0, 954, 0, 1, 0, 0, 954, 0, 0 ], [ 1, 0, 0.0079, 0.004, 0, 0.66, 0.0089, 796, 0, 1, 0, 0, 796, 0, 0 ], [ 2, 0, 0.0672, 0.1067, 0, 0.6...
[ "import numpy as np", "import numpy.linalg as nl", "def stripe_length(A):\n sup = -1\n inf = -1\n n = A.shape[0]\n\n #calcul de la largeur de la bande sup: ballayage des lignes\n #paralleles a la diagonale en commencant par la plus eloignee\n #de la diagonale (i.e l'element A(1,n))", " su...
import numpy as np import matplotlib.pyplot as plt import methodeIterative as mi import methodeDirecte as md #****************** Generations ************************************0 def generateMatrixHeat(n): A = np.zeros([n*n,n*n]) A += np.diag(-4*np.ones(n*n, dtype=np.int),0) A += np.diag(np.ones(n*n-1, dtype=np.int),1) A += np.diag(np.ones(n*n-1, dtype=np.int),-1) A += np.diag(np.ones(n*(n-1), dtype=np.int),-n) A += np.diag(np.ones(n*(n-1), dtype=np.int),n) return A #*********** Vectorialisation de la fonction de chauffage ***********1 # Deux fonctions qui etablissent une bijection: def convertMatVec(F): "Convertit la matrice F en vecteur" n = len(F) b = np.zeros(n*n) for i in range(n): for j in range(n): b[i*n+j] = F[i][j]; return b; def convertVecMat(x): "Converti le vecteur x en matrice" n = int(np.sqrt(len(x))) T = np.zeros([n,n]) for i in range(n): for j in range(n): T[i][j] = x[i*n+j] for x in range(n): T[x,0] = 0 T[x,n-1] = 0 for y in range(n): T[0,y] = 0 T[n-1,y] = 0 return T #******************* Deux fonctions de base **************************2 # Rq : nous initialisons le radiateur avec des nombres # negatifs car nous ne travaillons pas tout a fait # avec la temperature mais en raisonnant sur des # flux d'energie def generateRadiator(n): F = np.zeros([n,n]) if(n%2==0): F[(n/2)][(n/2)] = -np.sqrt(2)/np.log(n) # diviser par np.log(n)/sqrt(2) car # cela semble etre la valeur du point # le plus chaud (heuristique) F[(n/2)-1][(n/2)-1] = -np.sqrt(2)/np.log(n) F[(n/2)-1][(n/2)] = -np.sqrt(2)/np.log(n) F[(n/2)][(n/2)-1] = -np.sqrt(2)/np.log(n) else: F[(n-1)/2][(n-1)/2] = -4 * np.sqrt(2)/np.log(n) return F def generateWall(n): F = np.zeros([n,n]) for i in range(n): F[0][i] = -1 # ici on sait que l'energie evolue lineairement # en regime stationnaire # on suppose que l'on ne s'ecarte pas trop de # ce regime (changement lent de temperature) # donc le maximum devrait avoisinner 1 return F #************* Initialisations pratiques **************************** N = 20 A = generateMatrixHeat(N) bWall = convertMatVec(generateWall(N)) bRad = convertMatVec(generateRadiator(N)) #************** Fonction d'affichage ******************************** def display(T): n = len(T) # taille de la matrice carree for x in np.arange(0.,n,1.): for y in np.arange(0.,n,1.): plt.plot((x+1)/n, (y+1)/n,markeredgewidth=0, markersize=500.0/N, marker='s', color=(T[n-1-y][x],pow(T[n-1-y][x],2) ,0)) plt.show() #***************** Resultats **************************************** #********** Radiateur *********** # Methode iterative : # resultat = mi.resolIterative(mi.modeAffichageVersLocal(A),bRad, 20, mi.suivJacobi) # resultat = mi.resolIterative(mi.modeAffichageVersLocal(A),bRad, 20, mi.suivGauss) # resultat = mi.resolIterative(mi.modeAffichageVersLocal(A),bRad, 20, mi.suivRelax, mi.omega) # display(convertVecMat(resultat)) # Methode directe : #resultat = md.LU_solver(A, bRad) #display(convertVecMat(resultat)) # Resultat attendu : # display(convertVecMat(np.linalg.solve(A,bRad))) #*********** Mur ************ # Methode iterative : # resultat = mi.resolIterative(mi.modeAffichageVersLocal(A),bWall, 20, mi.suivJacobi) # resultat = mi.resolIterative(mi.modeAffichageVersLocal(A),bWall, 20, mi.suivGauss) # resultat = mi.resolIterative(mi.modeAffichageVersLocal(A),bWall, 20, mi.suivRelax, mi.omega) # display(convertVecMat(resultat)) # Les resultats semblent etre tres mauvais pour cette methode... # Methode directe : #resultat = md.LU_solver(A, bWall) #display(convertVecMat(resultat)) # Resultat attendu : #display(convertVecMat(np.linalg.solve(A, bWall)))
[ [ 1, 0, 0.0083, 0.0083, 0, 0.66, 0, 954, 0, 1, 0, 0, 954, 0, 0 ], [ 1, 0, 0.0167, 0.0083, 0, 0.66, 0.0769, 596, 0, 1, 0, 0, 596, 0, 0 ], [ 1, 0, 0.025, 0.0083, 0, 0...
[ "import numpy as np", "import matplotlib.pyplot as plt", "import methodeIterative as mi", "import methodeDirecte as md", "def generateMatrixHeat(n):\n A = np.zeros([n*n,n*n])\n A += np.diag(-4*np.ones(n*n, dtype=np.int),0)\n A += np.diag(np.ones(n*n-1, dtype=np.int),1)\n A += np.diag(np.ones(n*n...
def spacify(input, dict): """Given a string and a dictionary, if it is possible to seperate the string into a set of words that are in the dictionary, returns a string equivilant to the input string but with spaces between the valid dictionary words. If there is no way to break up the input string into a set of dictionary words, returns None.""" if len(input) == 0: return input first_n_spacified = [None for i in range(len(input) + 1)] first_n_spacified[0] = "" # padding the beginning to make the following code a bit cleaner for i in range(1, len(input)+1): # fill in the ith element of first_n_spacified for split in range(0,i): left = first_n_spacified[split] right = input[split:i] if left is not None and right in dict: first_n_spacified[i] = left + " " + right break return str.strip(first_n_spacified[-1]) if __name__ == "__main__": dict = {"two","blobs","walk","down","the","road","together","eating","peanut","butter","blob","do","he","to","ether","eat","pea","nut","butt","but","butter"} print(spacify("twoblobswalkdowntheroadtogethereatingpeanutbutter", dict))
[ [ 2, 0, 0.4643, 0.8214, 0, 0.66, 0, 404, 0, 2, 1, 0, 0, 0, 7 ], [ 8, 1, 0.1786, 0.1786, 1, 0.18, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 4, 1, 0.3393, 0.0714, 1, 0.18, 0...
[ "def spacify(input, dict):\n \"\"\"Given a string and a dictionary, if it is possible to seperate the string\n into a set of words that are in the dictionary, returns a string equivilant to\n the input string but with spaces between the valid dictionary words. If there\n is no way to break up the input ...
import codeJamUtils def _build_board(case): numRows, numCols, numMines = case freeSpaces = numCols * numRows - numMines board = [] doTransposeResult = False # for convenience make sure the board is either square or wider than it is tall if numRows > numCols: numCols, numRows = numRows, numCols doTransposeResult = True if numRows * numCols == numMines + 1: # edge case - there is only one free spot on the board board = [['*' for _ in range(numCols)] for _ in range(numRows)] board[0][0] = 'c' elif numRows == 1 and numCols >= numMines + 2: # if there is only one row, the problem is trivially solvable board.append((['*'] * numMines) + (['.'] * ((numCols - numMines) - 1)) + ['c']) elif numRows == 2: if freeSpaces > 3 and freeSpaces % 2 == 0: # A two row board is only solvable if there are > 3 free spaces and the number of free # spaces is even freeCols = freeSpaces // 2 board.append(['c'] + ['.' for _ in range(freeCols - 1)] + ['*' for _ in range(numCols - freeCols)]) board.append(['.' for _ in range(freeCols)] + ['*' for _ in range(numCols - freeCols)]) elif freeSpaces >= 4 and freeSpaces != 5 and freeSpaces != 7: # in the general case, we will arrange the board in an 'L" pattern like this: # c....... # ........ # ..****** # ..****** # ..****** # ..****** # Or this # c....*** # .....*** # ..****** # ..****** # ******** # ******** # fill with mines to start out board = [['*' for _ in range(numCols)] for _ in range(numRows)] # due to earlier condition checks, there must be at least 4 open spaces board[0][1] = board[1][0] = board[1][1] = '.' # set the click location board[0][0] = 'c' freeSpaces -= 4 add1At = (2,2) add2VertAt = 2 add2HorAt = 2 doAddOnes = False while freeSpaces > 0: if freeSpaces == 1: doAddOnes = True if not doAddOnes: if add2VertAt < numCols and (add2VertAt <= add2HorAt or add2HorAt >= numRows): board[0][add2VertAt] = '.' board[1][add2VertAt] = '.' freeSpaces -= 2 add2VertAt += 1 elif add2HorAt < numRows and (add2HorAt < add2VertAt or add2VertAt >= numCols): board[add2HorAt][0] = '.' board[add2HorAt][1] = '.' freeSpaces -= 2 add2HorAt += 1 else: # we've filled the "L." Now we can just fill one at a # time starting at the elbow doAddOnes = True else: board[add1At[0]][add1At[1]] = '.' freeSpaces -= 1 if add1At[1] == numCols - 1: # wrap to next row add1At = (add1At[0] + 1, 2) else: add1At = (add1At[0], add1At[1] + 1) if doTransposeResult: board = list(zip(*board)) return board def _board2str(board): output = "" for row in board: for character in row: output += character output += "\n" return str.strip(output) def _parse_input(inputLines): numCases = int(inputLines[0]) cases = [] for line in inputLines[1:]: numRows, numCols, numMines = str.split(line) cases.append((int(numRows), int(numCols), int(numMines))) return cases if __name__ == "__main__": inputLines = codeJamUtils.get_input_lines("minesweeperMaster.txt") cases = _parse_input(inputLines) for i, case in enumerate(cases): solution = _build_board(case) if (len(solution) == 0): codeJamUtils.write_output("minesweeperMaster.txt", i+1, "\nImpossible") else: codeJamUtils.write_output("minesweeperMaster.txt", i+1, "\n" + _board2str(solution)) fileIn.close() fileOut.close() # You want to win the game as quickly as possible. There is nothing quicker than # winning in one click. Given the size of the board (R x C) and the number of # hidden mines M, is it possible (however unlikely) to win in one click? You # may choose where you click. If it is possible, then print any valid mine # configuration and the coordinates of your click
[ [ 1, 0, 0.0079, 0.0079, 0, 0.66, 0, 573, 0, 1, 0, 0, 573, 0, 0 ], [ 2, 0, 0.373, 0.7063, 0, 0.66, 0.25, 118, 0, 1, 1, 0, 0, 0, 13 ], [ 14, 1, 0.0317, 0.0079, 1, 0.3...
[ "import codeJamUtils", "def _build_board(case):\n numRows, numCols, numMines = case\n freeSpaces = numCols * numRows - numMines\n board = []\n doTransposeResult = False\n\n # for convenience make sure the board is either square or wider than it is tall\n if numRows > numCols:", " numRows, n...
import codeJamUtils import operator def _calculate_optimal_deletions(case): numVerticies, adjacencyList = case # The key insight here is that only a single node in any full binary tree may serve as the # root (the only node with degree 2, as inner nodes have degree 3 and leaves degree 1). # It is relatively easy to pair nodes from a rooted tree until it is full and binary. return min((_calculate_num_deletions(root, None, adjacencyList)[0] for root in range(numVerticies))) def _calculate_num_deletions(root, parent, adjacencyList): """Computes the number of nodes in the subtree that would need to deleted in the best case in order to make this a full binary tree. Returns the number of deletions and the number of nodes remaining in the resulting full binary tree, as a tuple""" adjacentNodes = adjacencyList[root][:] if parent is not None: adjacentNodes.remove(parent) numChildren = len(adjacentNodes) if numChildren == 0: # No children -> this is already a full binary tree with 1 node. No deletions needed return (0, 1) elif numChildren == 1: # Too bad, we can't add nodes, so we have to delete the entire child's subtree, and # we end up with a single node full binary tree childDeletions, childSize = _calculate_num_deletions(adjacentNodes[0], root, adjacencyList) return (childDeletions + childSize, 1) elif numChildren == 2: child1Deletions, child1Size = _calculate_num_deletions(adjacentNodes[0], root, adjacencyList) child2Deletions, child2Size = _calculate_num_deletions(adjacentNodes[1], root, adjacencyList) return (child1Deletions + child2Deletions, child1Size + child2Size + 1) else: childDeletions = [0 for _ in range(numChildren)] childSizes = [0 for _ in range (numChildren)] for i in range(numChildren): childDeletions[i], childSizes[i] = _calculate_num_deletions(adjacentNodes[i], root, adjacencyList) # maximize the size of the subtrees we keep iChild = max(enumerate(childSizes), key = operator.itemgetter(1))[0] child1Size = childSizes[iChild] childSizes[iChild] = 0 iChild2 = max(enumerate(childSizes), key = operator.itemgetter(1))[0] child2Size = childSizes[iChild] childSizes[iChild] = 0 # We zero'd out the sizes in the array for the two children we're keeping # The total number of deletions was the number of deletions for each subtree, # plus the number of nodes in each subtree that we have to delete to get the # degree of root down to the appropriate number (i.e. must have two children) return sum(childDeletions) + sum(childSizes), child1Size + child2Size + 1 def _parse_input(lines): numCases = int(lines[0]) cases = [] lineNum = 1 for _ in range(numCases): numVerticies = int(lines[lineNum]) adjacencyList = [[] for _ in range(numVerticies)] lineNum += 1 for _ in range(numVerticies - 1): edge = str.split(lines[lineNum]) node1, node2 = int(edge[0]) - 1, int(edge[1]) - 1 adjacencyList[node1].append(node2) adjacencyList[node2].append(node1) lineNum += 1 cases.append((numVerticies, adjacencyList)) return cases if __name__ == "__main__": testCases = _parse_input(codeJamUtils.get_input_lines("fullBinaryTree.txt")) for i, case in enumerate(testCases): output = str(_calculate_optimal_deletions(case)) codeJamUtils.write_output("fullBinaryTree.txt", i+1, output) #A tree is a connected graph with no cycles. #A rooted tree is a tree in which one special vertex is called the root. If there #is an edge between X and Y in a rooted tree, we say that Y is a child of X if X is #closer to the root than Y (in other words, the shortest path from the root to X is #shorter than the shortest path from the root to Y). #A full binary tree is a rooted tree where every node has either exactly 2 children #or 0 children. #You are given a tree G with N nodes (numbered from 1 to N). You are allowed to #delete some of the nodes. When a node is deleted, the edges connected to the #deleted node are also deleted. Your task is to delete as few nodes as possible #so that the remaining nodes form a full binary tree for some choice of the #root from the remaining nodes. #Input #The first line of the input gives the number of test cases, T. T test cases follow. #The first line of each test case contains a single integer N, the number of nodes in #the tree. The following N-1 lines each one will contain two space-separated integers: #Xi Yi, indicating that G contains an undirected edge between Xi and Yi. #Output #For each test case, output one line containing "Case #x: y", where x is the test #case number (starting from 1) and y is the minimum number of nodes to delete from #G to make a full binary tree.
[ [ 1, 0, 0.0092, 0.0092, 0, 0.66, 0, 573, 0, 1, 0, 0, 573, 0, 0 ], [ 1, 0, 0.0183, 0.0092, 0, 0.66, 0.2, 616, 0, 1, 0, 0, 616, 0, 0 ], [ 2, 0, 0.0688, 0.055, 0, 0.66...
[ "import codeJamUtils", "import operator", "def _calculate_optimal_deletions(case):\n numVerticies, adjacencyList = case\n # The key insight here is that only a single node in any full binary tree may serve as the\n # root (the only node with degree 2, as inner nodes have degree 3 and leaves degree 1).\...
import codeJamUtils import sys def _find_best_flip_num(case): outletFlowStrs, deviceFlowStrs = case if (len(outletFlowStrs) == 0 or len(outletFlowStrs) != len(deviceFlowStrs)): return -1 L = len(outletFlowStrs[0]) # for each possible flip string, apply it to out outlet flows, and check that # each device str is present in the set. If they are, then the flip string is # feasible. Keep track of the best one seen so far minFlips = sys.maxsize # One approach: try every one of the possible 2^L strings i.e.: # for i in range(2**L): # # but to get faster, we can observe that since a given device (the first one, for # example, must be plugged into exacltly one of the outlets, we must chose a # flip string that causes at least on of the outlets to match the first device's # flow! for i in (int(deviceFlowStrs[0], 2) ^ int(o, 2) for o in outletFlowStrs): if bin(i).count('1') >= minFlips: # only consider flip strings with fewer flips than the min found so far continue newOutletFlows = { i ^ int(outletFlowStr, 2) for outletFlowStr in outletFlowStrs } isValid = True for deviceFlow in (int(deviceFlowStr, 2) for deviceFlowStr in deviceFlowStrs): if deviceFlow not in newOutletFlows: isValid = False break if isValid: minFlips = bin(i).count('1') if minFlips == sys.maxsize: return -1 else: return minFlips # If we wanted to generate the strings directly and didn't care about memory... #def _generate_all_binary_strings(l): # allStrings = [] # if l == 0: # return [''] # shorterStrings = _generate_all_binary_strings(l-1) # for s in shorterStrings: # allStrings.append(s + '0') # allStrings.append(s + '1') # return allStrings def _parse_input(lines): numCases = int(lines[0]) cases = [] for i in range(numCases): outletFlowsStr = lines[3*i + 2] deviceFlowsStr = lines[3*i + 3] outletFlowStrs = str.split(outletFlowsStr) deviceFlowStrs = str.split(deviceFlowsStr) cases.append((outletFlowStrs, deviceFlowStrs)) return cases if __name__ == "__main__": testCases = _parse_input(codeJamUtils.get_input_lines("chargingChaos.txt")) for i, case in enumerate(testCases): bestFlipNum = _find_best_flip_num(case) output = str(bestFlipNum) if (bestFlipNum == -1): output = "NOT POSSIBLE" codeJamUtils.write_output("chargingChaos.txt", i + 1, output)
[ [ 1, 0, 0.012, 0.012, 0, 0.66, 0, 573, 0, 1, 0, 0, 573, 0, 0 ], [ 1, 0, 0.0241, 0.012, 0, 0.66, 0.25, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 2, 0, 0.2771, 0.4699, 0, 0.66,...
[ "import codeJamUtils", "import sys", "def _find_best_flip_num(case):\n outletFlowStrs, deviceFlowStrs = case\n if (len(outletFlowStrs) == 0 or len(outletFlowStrs) != len(deviceFlowStrs)):\n return -1\n\n L = len(outletFlowStrs[0])\n\n # for each possible flip string, apply it to out outlet fl...
import codeJamUtils def compute_badrand_probability_matrix(N): M_nextiter = [[0.0 for _ in range(N)] for _ in range(N)] M_previter = [[0.0 for _ in range(N)] for _ in range(N)] i = N swapProb = 1/N noSwapProb = 1 - swapProb # working backwards from the last iteration of badrand, we can compute the # probability that the item at Source before iteration i (0 indexed) will # end up at Dest. We start with i = N, which represents the state after # badrand has completed all iterations. Since no swaps occur at this point # in badrand, we can initialize to probability 1 where Source = Dest and 0 # otherwise. for index in range(N): M_previter[index][index] = 1.0 while i > 0: # move "back in time" to the previous iteration M_nextiter = [M_previter[copyi][:] for copyi in range(N)] i -= 1 for source in range(N): # The ith iteration of badrand swaps the ith element with a random element if source == i: # The ith element before this iteration has an equal chance of ending # up at each place in the list after this iteration. Hence we can # compute the probability that this element ends up at dest with the # following formula p = sum(swapProb * M_nextiter[swap][dest] for swap in range(N)) for dest in range(N): M_previter[source][dest] = p else: for dest in range(N): # All of the other elements have a 1/N probability of being moved to # the ith position, and an 1 - 1/N probability of staying in the same # position. M_previter[source][dest] = (swapProb * M_nextiter[i][dest]) + (noSwapProb * M_nextiter[source][dest]) return M_previter; def guess_generated_by_badrand(permutation, badrand_probability_matrix): N = len(permutation) # We'll compute the probability of the given permutation being generated by # badrand, and compare to 1/n!, the probability of any permutation being # generated by proper rand. In order to keep the numbers in a reasonable range, # we'll incrementatlly multiply by factors of n! so that the final product # ends up being multiplied by n!. p = 1.0 for i in range(N): p *= badrand_probability_matrix[permutation[i]][i] p *= (N+1) if p > 1.0: return "BAD" else: return "GOOD" def _parse_input(inputLines): line = 1 numCases = int(inputLines[0]) cases = [] for _ in range(numCases): len = inputLines[line] line += 1 permutation = [int(c) for c in str.split(inputLines[line])] line += 1 cases.append(permutation) return cases if __name__ == "__main__": inputLines = codeJamUtils.get_input_lines("properShuffle.txt") cases = _parse_input(inputLines) N = len(cases[0]) badrand_probability_matrix = compute_badrand_probability_matrix(N) for i, case in enumerate(cases): codeJamUtils.write_output("properShuffle.txt", i+1, guess_generated_by_badrand(case, badrand_probability_matrix))
[ [ 1, 0, 0.012, 0.012, 0, 0.66, 0, 573, 0, 1, 0, 0, 573, 0, 0 ], [ 2, 0, 0.2831, 0.506, 0, 0.66, 0.25, 595, 0, 1, 1, 0, 0, 0, 11 ], [ 14, 1, 0.0602, 0.012, 1, 0.53, ...
[ "import codeJamUtils", "def compute_badrand_probability_matrix(N):\n\n M_nextiter = [[0.0 for _ in range(N)] for _ in range(N)]\n M_previter = [[0.0 for _ in range(N)] for _ in range(N)]\n i = N\n\n swapProb = 1/N\n noSwapProb = 1 - swapProb", " M_nextiter = [[0.0 for _ in range(N)] for _ in r...
import codeJamUtils import sys def _compute_time(case): farmCost, farmRate, goal = case maxRate = 2 prevTime = sys.maxsize curTime = goal / 2 while curTime <= prevTime: prevTime = curTime # go back to before we went for goal curTime -= goal/maxRate # and this time go for another farm first curTime += farmCost / maxRate maxRate += farmRate curTime += goal / maxRate return prevTime def _parse_input(inputLines): numCases = int(inputLines[0]) cases = [] for line in inputLines[1:]: farmCost, farmRate, goal = str.split(line) cases.append((float(farmCost), float(farmRate), float(goal))) return cases if __name__ == "__main__": inputLines = codeJamUtils.get_input_lines("cookieClicker.txt") cases = _parse_input(inputLines) for i, case in enumerate(cases): codeJamUtils.write_output("cookieClicker.txt", i+1, _compute_time(case)) #In this problem, you start with 0 cookies. You gain cookies at a rate of 2 cookies #per second, by clicking on a giant cookie. Any time you have at least C cookies, #you can buy a cookie farm. Every time you buy a cookie farm, it costs you C cookies #and gives you an extra F cookies per second. #Once you have X cookies that you haven't spent on farms, you win! Figure out how #long it will take you to win if you use the best possible strategy.
[ [ 1, 0, 0.0222, 0.0222, 0, 0.66, 0, 573, 0, 1, 0, 0, 573, 0, 0 ], [ 1, 0, 0.0444, 0.0222, 0, 0.66, 0.25, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 2, 0, 0.2778, 0.4, 0, 0.66,...
[ "import codeJamUtils", "import sys", "def _compute_time(case):\n farmCost, farmRate, goal = case\n\n maxRate = 2\n prevTime = sys.maxsize\n curTime = goal / 2\n\n while curTime <= prevTime:", " farmCost, farmRate, goal = case", " maxRate = 2", " prevTime = sys.maxsize", " curT...
import codeJamUtils def _compute_scores(case): return (_compute_optimal_deceitful_war_score(case), _compute_optimal_war_score(case)) def _compute_optimal_war_score(case): # in war, p1 has no information about the weights of p2's blocks. p1 can assume # that p2 will use a greedy algorithm; for each block B with weight W_b that she # chooses, he will choose the block B' in his collection with weight W_b' > W_b # such that W_b' - W_b is minimized. If no such block exists, he will choose the # block in his collection with the smallest weight # The outcome in this case is fixed based on the initial weights of the blocks # allocated to the two players. There is no way for p1 to cause p2 to unnecessarily # use a larger-weight block. Therefore to determine the optimal score for p1, we # simply simulate the game in any order of play. # these are assumed to be sorted p1BlockWeights, p2BlockWeights = case[0][:], case[1][:] p1Points = 0 for p1Block in p1BlockWeights: p2Choice = None for p2Block in p2BlockWeights: if p2Block > p1Block: # win for p2 p2Choice = p2Block break if p2Choice is None: # no winning block for p2 was found. point for p1 p1Points += 1 p2Choice = p2BlockWeights[0] p2BlockWeights.remove(p2Choice) return p1Points def _compute_optimal_deceitful_war_score(case): return len(case[0]) - _compute_optimal_war_score((case[1], case[0])) def _parse_input(lines): numCases = int(lines[0]) cases = [] for i in range(1, len(lines), 3): p1BlockWeights = sorted(map(lambda weightStr: float(weightStr), list(str.split(lines[i+1])))) p2BlockWeights = sorted(map(lambda weightStr: float(weightStr), list(str.split(lines[i+2])))) cases.append((p1BlockWeights, p2BlockWeights)) return cases if __name__ == "__main__": testCases = _parse_input(codeJamUtils.get_input_lines("deceitfulWar.txt")) for i, case in enumerate(testCases): scores = _compute_scores(case) codeJamUtils.write_output("deceitfulWar.txt", i + 1, str.format("{0} {1}", scores[0], scores[1]))
[ [ 1, 0, 0.0172, 0.0172, 0, 0.66, 0, 573, 0, 1, 0, 0, 573, 0, 0 ], [ 2, 0, 0.0603, 0.0345, 0, 0.66, 0.2, 609, 0, 1, 1, 0, 0, 0, 2 ], [ 13, 1, 0.069, 0.0172, 1, 0.78,...
[ "import codeJamUtils", "def _compute_scores(case):\n return (_compute_optimal_deceitful_war_score(case), _compute_optimal_war_score(case))", " return (_compute_optimal_deceitful_war_score(case), _compute_optimal_war_score(case))", "def _compute_optimal_war_score(case):\n # in war, p1 has no informati...
if __name__ == "__main__": pass
[ [ 4, 0, 0.9286, 0.2857, 0, 0.66, 0, 0, 0, 0, 0, 0, 0, 0, 0 ] ]
[ "if __name__ == \"__main__\":\n pass" ]
def get_input_lines(filename): with open("CodeJamSolutions\\Input\\" + filename) as inputFile: return inputFile.readlines() def write_output(filename, caseNum, result): mode = "a" if caseNum == 1: mode = "w" with open("CodeJamSolutions\\Output\\" + filename, mode) as outputFile: outputFile.write(str.format("Case #{0}: {1}\n", caseNum, result))
[ [ 2, 0, 0.2308, 0.2308, 0, 0.66, 0, 34, 0, 1, 1, 0, 0, 0, 2 ], [ 13, 1, 0.3077, 0.0769, 1, 0.98, 0, 0, 3, 0, 0, 0, 0, 10, 1 ], [ 2, 0, 0.7692, 0.5385, 0, 0.66, ...
[ "def get_input_lines(filename):\n with open(\"CodeJamSolutions\\\\Input\\\\\" + filename) as inputFile:\n return inputFile.readlines()", " return inputFile.readlines()", "def write_output(filename, caseNum, result):\n mode = \"a\"\n if caseNum == 1:\n mode = \"w\"\n\n with open(...