def main(options): if options.test: filename = 'sample.txt' else: filename = 'input.txt' initial_state, rules = read_input(filename) automat = Automat(initial_state, rules) print(automat.current_state) solution = sum([ k for k in automat.current_state.cells if automat.current_state.cells[k] == 1 ]) for i in range(22): automat.evolve() print(automat.current_state) old_value = solution solution = sum([ k for k in automat.current_state.cells if automat.current_state.cells[k] == 1 ]) # print(f'Step {i} solution in {solution} diff {solution-old_value}') def f(x): return 10617 + (x - 120) * 69 solution = f(50000000000 - 1) print(f'Solution of part 2 is {solution}')
def main(options): filename = 'three_crosses_2.txt' state = read_input(filename) for frame in range(0, 150): print('--[Frame {}]-------------------'.format(frame)) for car in state.get_cars(): print(repr(car)) draw_frame(state, frame) state.tick()
def input_samples(self, s=None): """Parse the samples if given in s, or input from console. """ if not s: s = read_input('Individual samples (space or comma separated)') self.members = re.findall(r"[\w\.\-\+]+", s) self.members = [m.strip() for m in self.members] self.members = [float(m) for m in self.members if m] self._update_parameters()
def input_wizard(self, csv_filename=None, csv_indices=None): """Read input from the console interactively. """ if csv_filename: self.load_from_csv(csv_filename, csv_indices=csv_indices) else: while True: samp = Sample(title='samp%d' % len(self.groups), is_population=False) samp.input_wizard(require_n=True) if not samp.n: break self.groups.append(samp) more = read_input('Input more sample', default='y', choices='yn') if more != 'y': break self.alpha = float(read_input("Alpha", default='%.03f' % self.alpha))
def input_wizard(self, require_n=False, ref_pop=None, individual_sample=None, csv_filename=None, csv_indices=None): """Wizard to input the parameters from console. """ if not csv_filename: s = read_input('The name of this sample', default=self.title, optional=True) if s: self.title = s if self.is_population is None: s = read_input('Treat as population', default='n', choices=['y', 'n']) self.is_population = True if s == 'y' else False if csv_filename: col_idx = csv_indices[0] if csv_indices else 0 self.load_from_csv(csv_filename, col_idx) return self if not self.title: self.title = "population" if self.is_population else "sample" if individual_sample is None: s = read_input('Input parameters or individual sample', default='p', choices=['p', 'i']) individual_sample = s == 'i' if not individual_sample: s = read_input('n (number of data)', optional=not require_n) if s: self.n = int(s) self.mean = self.orig_mean = float(read_input('Mean')) if ref_pop and (not ref_pop.is_population or ref_pop.sd is None): ref_pop = None title = 'Standard deviation%s: ' % \ (' (skip to calculate from population)' if ref_pop else '') s = read_input(title, optional=True) if s: self.sd = self.orig_sd = float(s) elif ref_pop: self.sd = ref_pop.sd / math.sqrt(self.n) self.notes = "SD is derived from population" print( "Note: Calculating SD as Standard Error from population.") print(" SE: %.3f." % self.sd) else: self.input_samples() return self
def input_wizard(self, csv_filename=None, csv_indices=None): """Read input from the console interactively. """ if csv_filename: self.load_from_csv(csv_filename, csv_indices=csv_indices) else: while True: print("Set title to 'Expected' to make it the expected group") samp = Sample(title='Observed-%d' % len(self.groups), is_population=False) samp.input_wizard(individual_sample=True) if not samp.n: break if samp.title.lower() == 'expected': self.expected_index = len(self.groups) self.groups.append(samp) more = read_input('Input more sample', default='y', choices='yn') if more != 'y': break self.alpha = float(read_input("Alpha", default='0.05'))
def input_wizard(self, csv_filename=None, csv_indices=None): """Wizard to input the parameters from console. """ if csv_filename: col_idx = csv_indices[0] if csv_indices else 0 self.samp0.load_from_csv(csv_filename, col_idx) col_idx = csv_indices[1] if csv_indices and len(csv_indices) > 1 else col_idx + 1 self.samp1.load_from_csv(csv_filename, col_idx) else: print("Input the first sample (samp0)") self.samp0.input_wizard() print("") print("Input the second sample (samp1)") ref_pop = self.samp0 if self.samp0.is_population else None self.samp1.input_wizard(require_n=True, ref_pop=ref_pop) print("Info: mean difference: %.3f" % self.mean_difference()) self._fix_samples() print("") independent_t_test = self.__class__.__name__ == "IndependentTTesting" if not independent_t_test: self.treatment_title = read_input("The name of the treatment", default=self.treatment_title, optional=True) self.results_title = read_input("The name of the results", default=self.results_title, optional=True) self.dir = read_input('Directionality: Two tailed (t), one tailed negative (n), or one tailed positive (p)', default=StatTool.TWO_TAILED_TEST, choices=StatTool.valid_dirs) self.alpha = float(read_input("Alpha", default='%.03f' % self.alpha)) self.expected_difference = float(read_input("Expected difference", default='0.0', optional=True)) print("Critical value: %.3f" % self.critical()) return self
def main(options): if options.test: filename = 'sample.txt' output = 'sample.grafel' else: filename = 'input.txt' output = 'input.grafel' dots = collections.OrderedDict() for name, dot in zip(get_names(), read_input(filename)): dots[name] = dot max_x = dots[max(dots, key=lambda k: dots[k].pos.x)].pos.x min_x = dots[min(dots, key=lambda k: dots[k].pos.x)].pos.x print('Range of x is [{} .. {}]'.format(min_x, max_x)) max_y = dots[max(dots, key=lambda k: dots[k].pos.y)].pos.y min_y = dots[min(dots, key=lambda k: dots[k].pos.y)].pos.y print('Range of y is [{} .. {}]'.format(min_y, max_y)) zoom = 512 left_top = Vector2(min_x // zoom, min_y // zoom) right_bottom = Vector2(max_x // zoom, max_y // zoom) scale = Scale(left_top, right_bottom) print(f'Generating {output}', end=' ') with open(output, 'w') as fh: fh.write('Cast:\n\n') for name in dots: d = dots[name] x, y = scale(d.pos) x, y = d.pos print(f' {name} = Circle pos {x}x{y} radius 1 color white', file=fh) fh.write('Actions:\n\n') for name in dots: dot = dots[name] x, y = scale(dot.pos) print(f' 0-25 EaseIn {name} {x}x{y}', file=fh) step_size = 2 for frame in range(options.steps - 100): for name in dots: dot = dots[name] dot.pos = dot.pos + dot.vel print('.', end='', flush=True) for frame in range(25): for name in dots: dot = dots[name] for _ in range(4): dot.pos = dot.pos + dot.vel x, y = scale(dot.pos) print(f' {100+frame}-{100+frame+1} EaseIn {name} {x}x{y}', file=fh) print('[OK]')
def main(options): if options.test: filename = 'sample.txt' else: filename = 'input.txt' initial_state, rules = read_input(filename) automat = Automat(initial_state, rules) print(automat.current_state) for i in range(20): automat.evolve() solution = sum([ k for k in automat.current_state.cells if automat.current_state.cells[k] == 1 ]) print(f'Solution of part 1 is {solution}')
def evaluate_phrases(input_file, gold_phrases_file, dev_phrases_file): sentences = read_input(input_file) gold_phrases = read_phrases(gold_phrases_file) dev_phrases = read_phrases(dev_phrases_file) comparison = compare_phrases(gold_phrases, dev_phrases) print("# Task A (detecting phrases)") print("# input file: %s" % input_file) print("# gold file: %s" % gold_phrases_file) print("# dev file: %s" % dev_phrases_file) print('\n* Correct (%i):' % len(comparison['correct'])) for item in comparison['correct']: item["text"] = get_span(sentences, item) print(u' - "{text}" from {start} to {end}.'.format(**item)) print('* Partial (%i):' % len(comparison['partial'])) for item, other in comparison['partial']: item["text"] = get_span(sentences, item) other["text"] = get_span(sentences, other) print(u' - "{text}" from {start} to {end}'.format(**item), end="") print(u' vs "{text}" from {start} to {end}.'.format(**other)) print('* Missing (%i):' % len(comparison['missing'])) for item in comparison['missing']: item["text"] = get_span(sentences, item) print(u' - "{text}" from {start} to {end}.'.format(**item)) print('* Spurious (%i):' % len(comparison['spurious'])) for item in comparison['spurious']: item["text"] = get_span(sentences, item) print(u' - "{text}" from {start} to {end}.'.format(**item)) ok = len(comparison['correct']) + 0.5 * len(comparison['partial']) precision = ok / (ok + len(comparison['spurious'])) recall = ok / (ok + len(comparison['missing'])) f1 = 2 * precision * recall / (precision + recall) print("\nPrecision = %.2f\nRecall = %.2f\nF1 Score = %.2f" % (precision, recall, f1)) return sentences, gold_phrases, dev_phrases, comparison['mapping']
def main(options): if options.test: filename = 'sample2.txt' else: filename = 'input.txt' state = read_input(filename) while True: state.tick() if state.crashed: print('Crashed: {}'.format(state.crashed)) state.cars = [ car for car in state.cars if car not in state.crashed ] print('current num of cars: {}'.format(len(state.cars))) if len(state.cars) == 1: break print(state) print(state.cars) car = state.cars[0] solution = '{},{}'.format(car.x, car.y) print('Solution of parf 2 is {}'.format(solution))
def main(options): output = 'frames/frame_{:04d}.png' if options.test: filename = 'sample.txt' else: filename = 'input.txt' state = read_input(filename) frame = 0 print(state) draw_frame(state, frame) while True: state.tick() frame += 1 draw_frame(state, frame) if state.crashed: print('Found crash') print('crashed: {} {}'.format(state.crashed, type(state.crashed))) print(state) a, *b = list(state.crashed) solution = '{},{}'.format(a.x, a.y) print('Solution of part 1 is {}'.format(solution)) break
for i in top_n: cluster = 'C%s'%(str(i)) gmmname = gmm.adapt(attr,cluster,ubmname) cluster_gmms[cluster] = gmmname # Resegmentation hmmname = '%s/%s_hmm.txt'%(out,basename) resegment.viterbi(attr,cluster_gmms,hmmname) labs,starts,ends = tools.merge_segs(attr['viterbi'],attr['sad']) return labs,starts,ends if __name__=='__main__': root_dir = './' out=tools.prepare_root(root_dir) wavname,ubmname = tools.read_input() basename = tools.gen_uid(wavname) attr = tools.gen_attr(out,basename,wavname) # SAD sad.run_sad(attr) # MFCC feat.run_mfcc(attr) # BIC bic.run_bic(attr,'uniform') # CLUSTERING cluster.run_clustering(attr)
#!/usr/bin/env python3 import tools import heapq all_tasks = set() for task_0, task_1 in tools.read_input('input.txt'): all_tasks.add(task_0.name) all_tasks.add(task_1.name) roots = tools.Task.find_roots() print('Roots are {}'.format(roots)) stack = [t.name for t in roots] heapq.heapify(stack) executed = set() buff = [] while stack: print(stack) for nn in stack: print(tools.Task.get(nn)) found_next = False descards = set([]) while True: name = heapq.heappop(stack) task = tools.Task.get(name) if task.is_ready(): break
from __future__ import print_function from tools import Task, Scheduler, read_input testing = not True if testing: filename = 'sample.txt' num_workers = 2 offset = 0 else: filename = 'input.txt' num_workers = 5 offset = 60 all_tasks = set() for task_0, task_1 in read_input(filename): all_tasks.add(task_0.name) all_tasks.add(task_1.name) roots = Task.find_roots() stack = list(sorted([t.name for t in roots])) sch = Scheduler(num_workers, offset) seen = set(stack) for name in stack: task = Task.get(name) sch.add(task) buff = [] counter = 0 while stack: counter += 1 # print(stack)
#!/usr/bin/env python import tools import collections if __name__ == '__main__': by_date = collections.defaultdict(list) for (code, day, hhmm, msg, guard_id) in tools.read_input(): by_date[day].append((code, hhmm, guard_id)) print(code) print( ' '*12, '000000000011111111112222222222333333333344444444445555555555' ) print( ' '*12, '012345678901234567890123456789012345678901234567890123456789' ) max_sleep = 0 max_sleep_safe = 0 max_day = None max_guard_id = None stat_guards = collections.defaultdict(int) buff = [] for day in by_date: m = tools.Mapa(day) for (code, hhmm, guard_id) in by_date[day]: m.add(code, hhmm, guard_id) print(m) if m.guard_id == 727:
#!/usr/bin/env python3 import tools from collections import defaultdict if __name__ == "__main__": mapa = defaultdict(int) max_cols = 0 max_rows = 0 for claim in tools.read_input(transform=tools.parse): max_cols = max(max_cols, claim.left + claim.width) max_rows = max(max_rows, claim.top + claim.height) for (x, y) in claim: mapa[(x, y)] += 1 # tools.print_mapa(mapa, max_cols, max_rows) acc = 0 for x in range(max_cols): for y in range(max_rows): if mapa[(x, y)] > 1: acc += 1 print(f"Solution for part 1: {acc}")
#!/usr/bin/env python3 from tools import read_input, create_tree root = create_tree(read_input('input.txt')) solution = root.value() print('Solution of part 2 in {}'.format(solution))
import sys sys.path.append('../code/') import tools import sad import feat import cluster import bic root_dir = './' out = tools.prepare_root(root_dir) wavname, _ = tools.read_input() basename = tools.gen_uid(wavname) attr = tools.gen_attr(out, basename, wavname) sad.run_sad(attr) feat.run_mfcc(attr) bic.run_bic(attr, 'uniform') cluster.run_clustering(attr)