def getCodechefProblem(problemUrl): count = 0 # driver = webdriver.Chrome('C:\Users\Pranay\Downloads\Setups\Drivers\chromedriver.exe') #Get problem Name problemName = '' for c in problemUrl[::-1]: if c == '/': break problemName = problemName + c problemName = problemName[::-1] driver.get(problemUrl) print('reach problem page ' + problemUrl) try: problemText = '' divProblem = WebDriverWait(driver, 5).until( EC.presence_of_element_located((By.ID, "problem-page-complete"))) divProblem = driver.find_element_by_id('problem-page-complete') #print(str(divProblem)) print('problem content got') all_children_by_xpath = divProblem.find_elements_by_xpath(".//*") for child in all_children_by_xpath: problemText = problemText + ' ' + child.text allHrefTags = driver.find_elements_by_tag_name('a') problemTags = '' for hrefTag in allHrefTags: if 'tag' in hrefTag.get_attribute('href'): problemTags = problemTags + ' ' + hrefTag.text prob = Problem(problemName, problemUrl, problemTags, problemText) # print(problemText) # print(prob) count = count + 1 return prob except Exception as e: print('element not found') print(e) with open('codechef/unscuccessful', 'a') as f: f.write(problemName + '\n') return None
def solve(solver_name, problem_name, options): 'Solve the problem by solver with options.' # Set cpp_compiler options parameters["form_compiler"]["cpp_optimize"] = True # Set debug level set_log_active(options['debug']) # Set refinement level options['N'] = mesh_sizes[options['refinement_level']] # Create problem and solver problem = Problem(problem_name, options) solver = Solver(solver_name, options) time_step = solver.get_timestep(problem)[0] if MPI.process_number() == 0 and options['verbose']: print 'Problem: ' + str(problem) print 'Solver: ' + str(solver) # Solve problem with solver wct = time.time() u, p = solver.solve(problem) # Compute elapsed time wct = time.time() - wct # Compute number of degrees of freedom num_dofs = u.vector().size() + p.vector().size() # Get the mesh size mesh_size = u.function_space().mesh().hmin() # Get functional value and error functional, error = solver.eval() # Save results cpu_time = solver.cputime() save_results(problem, solver, num_dofs, mesh_size, time_step, functional, error) return 0
#dataset = SyntheticDataSet(nImg=100, K=10, p=0.5) dataset = WillowDataSet() Xin, Xgt, dimGroup = dataset.getData() # define the manifold manifold = MultinomialManifold(dimGroup.sum(), dataset.K) # pick a solver #solver = GradientDescent(tol = 1e-3, learning_rate = 0.05, max_iter = 500) solver = ConjugateGradient(tol = 1e-2, max_iter = 500) # define initial point X0 = manifold.random() # define the problem problem = Problem(Xin, dimGroup) # minimize the objective of the problem using solver cache, X = solver.Solve(manifold, problem.cost, problem.egrad, X0) # discretize low-rank factors discretization = Discretization(X, dimGroup) X = discretization.Stochastic2Permutation() # evaluate accuracy evaluation = Eval(Xin, Xgt, X) evaluation.print_accuracy() # plot cost over time plots = Plots(cache) plots.plot_cost()
import mathtools as mt from problems import Problem problem = Problem( problem_id=7, actual_args_dict=dict(prime_index=10001), solution=None, ) @problem.list_as_solver def main(args): return mt.item_by_index(mt.primes(), args.prime_index)
''' Created on May 26, 2012 @author: Joe Lei ''' import logging import logging.config logging.config.fileConfig('../etc/logging.ini') log=logging.getLogger('euler') from problems import Problem if __name__=="__main__": result=Problem(59).run() log.info(result)
def main(args): 'Parse command-line arguments and run solver' # Check arguments if not len(args) >= 2: usage() return 2 # Get problem and solver problem_name, solver_name = args[:2] # Get options options = OPTIONS.copy() for arg in args[2:]: try: key, value = arg.split('=') try: options[key] = eval(value) except: options[key] = str(value) except: print 'Warning: Unhandled command-line argument', arg # Parse the spatial and time stepping options. # If either refinement_level or dt_division are lists feed the items of # list one by one type_dx = type(options['refinement_level']) type_dt = type(options['dt_division']) if type_dx is list: if type_dt is int: # Do a dx convergence study if MPI.process_number() == 0: print_color( 'Dx convergence study, dt=%d' % options['dt_division'], 'cyan') refinement_levels = copy.copy(options['refinement_level']) # loop over dx for refinement_level in refinement_levels: if MPI.process_number() == 0: print_color('\tRefinement level %d' % refinement_level, 'yellow') options['refinement_level'] = refinement_level # solve with fixed dt and changing dx # Warn user about running dx convergence with changing dt, this happens # if problem has no dt _options = options.copy() _options['N'] = mesh_sizes[_options['refinement_level']] _problem = Problem(problem_name, _options) if _problem.dt is None: print_color( ' Warning: Dx convergence study with changing dt', 'pink') solve(solver_name, problem_name, options) else: raise ValueError( 'Use fixed dt_division with changing refinement_level!') elif type_dx is int: if type_dt is list: # Do a dt convergence study if MPI.process_number() == 0: print_color( 'Dt convergence study, dx=%d' % options['refinement_level'], 'cyan') dt_divisions = copy.copy(options['dt_division']) # loop over dt for dt_division in dt_divisions: if MPI.process_number() == 0: print_color('\tDt division %d' % dt_division, 'yellow') options['dt_division'] = dt_division #solve with fixed dx and changing dt solve(solver_name, problem_name, options) elif type(options['dt_division']) is int: if MPI.process_number() == 0: print_color('Fixed dx and dt', 'cyan') # solve with fixed dx and fixed dt solve(solver_name, problem_name, options) else: raise ValueError("options['dt_division'] must be int of list!") else: raise ValueError("options['refinement_level'] must be int of list!") return 0
import mathtools as mt from problems import Problem problem = Problem( problem_id=3, actual_args_dict=dict(number=600851475143), solution=None, ) @problem.list_as_solver def main(args): return mt.item_by_index(mt.prime_factors(args.number), -1)
import mathtools as mt from problems import Problem problem = Problem( problem_id=6, actual_args_dict=dict(max=100), solution=None, ) @problem.list_as_solver def main(args): sum_of_squares = sum(n**2 for n in range(args.max + 1)) square_of_sum = mt.arithmetic_series(args.max + 1)**2 return square_of_sum - sum_of_squares
import itertools import mathtools as mt from problems import Problem problem = Problem( problem_id=2, actual_args_dict=dict(max=4 * 10**6), solution=4613732, ) # A fibonacci number is even iff its index is 0 (mod 3). # A closed-form solution is hard to implement because of precision issues. @problem.list_as_solver def check_parity(args): fibonacci_numbers = mt.items_up_to(mt.fibonacci_numbers(), args.max + 1) even_fibonacci_numbers = (fib for fib in fibonacci_numbers if fib % 2 == 0) return sum(even_fibonacci_numbers) @problem.list_as_solver def every_third(args): fibonacci_numbers = mt.items_up_to(mt.fibonacci_numbers(), args.max + 1) even_fibonacci_numbers = itertools.islice(fibonacci_numbers, 0, None, 3) return sum(even_fibonacci_numbers) @problem.list_as_solver
import mathtools as mt from problems import Problem problem = Problem( problem_id=4, actual_args_dict=dict(num_digits=3), solution=None, ) @problem.list_as_solver def main(args): start = 10**(args.num_digits - 1) stop = 10**args.num_digits products = (a * b for a in range(start, stop) for b in range(a, stop)) palindromes = (n for n in products if mt.is_decimal_palindrome(n)) return max(palindromes)
def getCodechefProblem(problemUrl, difficulty='unknown'): print problemUrl driver = getDriver() count = 0 print problemUrl # driver = webdriver.Chrome('C:\Users\Pranay\Downloads\Setups\Drivers\chromedriver.exe') # submissionPageQuery = "?sort_by=All&sorting_order=asc&language=All&status=15&handle=&Submit=GO" #Get problem Name problemName = '' for c in problemUrl[::-1]: if c == '/': break problemName = problemName + c problemName = problemName[::-1] driver.get(problemUrl) print('reach problem page ' + problemUrl) try: problemText = '' divProblem = WebDriverWait(driver, 5).until( EC.presence_of_element_located((By.ID, "problem-page-complete"))) divProblem = driver.find_element_by_id('problem-page-complete') print('problem content got') all_children_by_xpath = divProblem.find_elements_by_xpath(".//*") for child in all_children_by_xpath: problemText = problemText + ' ' + child.text allHrefTags = driver.find_elements_by_tag_name('a') problemTags = '' for hrefTag in allHrefTags: if 'tag' in hrefTag.get_attribute('href'): problemTags = problemTags + ' ' + hrefTag.text medianSubmissionSize = 0.0 submissionSizes = [] totalSub = 0 successDiv = driver.find_element_by_id('success-submissions') plusButton = successDiv.find_element_by_tag_name('button') plusButton.click() flag = True while flag: tableTag = WebDriverWait(driver, 5).until( EC.presence_of_element_located((By.CLASS_NAME, "dataTable"))) tableTag = driver.find_element_by_class_name('dataTable') bodyTag = tableTag.find_element_by_tag_name('tbody') allRowTags = bodyTag.find_elements_by_tag_name('tr') for rowTag in allRowTags: if len(submissionSizes) >= 100: flag = False break allDataTags = rowTag.find_elements_by_tag_name('td') if len(allDataTags) > 3: if "c" in allDataTags[3].text.lower(): totalSub = totalSub + 1 submissionSizes.append( float(re.sub("[^0-9, .]", "", allDataTags[2].text))) totalSub = totalSub + 1 if flag == False: break successDiv = driver.find_element_by_id('success-submissions') aTags = successDiv.find_elements_by_tag_name('a') if aTags is None: break flag = False #print 'searching onclick for next' for aTag in aTags: try: onclickAttr = aTag.get_attribute('onclick') if onclickAttr is not None and 'next' in onclickAttr: flag = True #print 'clicking next button' aTag.click() time.sleep(2) break except Exception as e: print(e) exc_type, exc_obj, exc_tb = sys.exc_info() print 'Exception at line ' + str(exc_tb.tb_lineno) logging.error( 'Time: {0} File: {1} Line: {2} Caused By: {3}'.format( datetime.datetime.now(), os.path.basename(__file__), exc_tb.tb_lineno, e)) # logging.error(str(datetime.datetime.now()) + ' :File Name: '+ str(os.path.basename(__file__)) + # ' :Line Number: '+ str(exc_tb.tb_lineno) + ' :Caused By: ' + str(e)) # print e # exc_type, exc_obj, exc_tb = sys.exc_info() # print exc_tb.tb_lineno onclickAttr = None submissionSizes.sort() medianSubmissionSize = submissionSizes[(len(submissionSizes) - 1) / 2] print str(medianSubmissionSize) + " median submission size" prob = Problem(problemName, problemUrl, problemTags, problemText, difficulty, medianSubmissionSize) count = count + 1 driver.close() return prob except Exception as e: print('Exception raised') print(e) exc_type, exc_obj, exc_tb = sys.exc_info() print 'Exception at line ' + str(exc_tb.tb_lineno) logging.error( 'Time: {0} File: {1} Line: {2} Caused By: {3} Problem Name: {4}'. format(datetime.datetime.now(), os.path.basename(__file__), exc_tb.tb_lineno, e, problemName)) # logging.error(str(datetime.datetime.now()) + ' :File Name: '+ str(os.path.basename(__file__)) + # ' :Line Number: '+ str(exc_tb.tb_lineno) + ' :Caused By: ' + str(e)) try: with open('codechef/unscuccessful', 'a') as f: f.write(problemName + '\n') except: pass driver.close() return None
import mathtools as mt import typetools as tt from problems import Problem problem = Problem( problem_id=1, actual_args_dict=dict( divisors=frozenset({3, 5}), stop=1000, ), domain=dict( divisors=tt.SetOf(tt.positive_int), stop=tt.natural_number, ), solution=233168, ) @problem.list_as_solver def iterator_based(args): def is_multiple(n): return any(n % d == 0 for d in args.divisors) multiples = (n for n in range(args.stop) if is_multiple(n)) return sum(multiples) @problem.list_as_solver def add_each(args): total = 0 for n in range(args.stop):