def main_two(): data = utils.read_input_file(to_array).astype(int) oxy_rating = process_list(data, get_most_common_bit) co2_rating = process_list(data, get_least_common_bit) print( "The oxygen generator rating is {}, CO2 scrubber rating is {}. The life support rating is {}" .format(oxy_rating, co2_rating, oxy_rating * co2_rating))
def read_input_data(filename="input01.txt"): result_list = read_input_file(filename) rows = int(result_list[0].strip('\n')) result = [] for index in range(rows): result.append([result_list[2*index + 1].strip('\n'), float(result_list[2*index + 2].strip('\n'))]) return result
def main(invalid_number: int): numbers = utils.read_input_file("xmas_cypher.txt") for pointer in range(len(numbers) - 1): found, high = find_contiguous_values_equal_to_value( numbers, pointer, invalid_number) if found: weak_data = numbers[pointer:high] return min(weak_data) + max(weak_data)
def main(bag_colour): number_of_bags_needed = 0 rules = utils.read_input_file("baggage_rules.txt") bags = dict() for rule in rules: bags.update(get_bags_in_bag(rule)) my_bag_contains = sum([int(x[0]) for x in bags[bag_colour]]) print(my_bag_contains) return number_of_bags_needed
def main(): grouped_answers = utils.read_input_file( "customs_declaration_form_questions.txt") sum_of_counts = 0 for group_answers in grouped_answers: combined_answers = set( [x for z in group_answers for y in z for x in y]) sum_of_counts += len(combined_answers) print(f"Sum of counts: {sum_of_counts}")
def main(preamble_length: int = 25): numbers = utils.read_input_file("xmas_cypher.txt") index = preamble_length while index < len(numbers) - 1: start = index - preamble_length if index - preamble_length - 1 > 0 else 0 if not find_sum_of_combination_equal_to_value(numbers[start:index], numbers[index]): return numbers[index] index += 1 return None
def main(): number_of_valid_passorts = 0 passport_details = utils.read_input_file("passport_details.txt") for passport_detail in passport_details: try: Passport(**passport_detail) except TypeError: pass else: number_of_valid_passorts += 1 print(f"Valid passports found: {number_of_valid_passorts}")
def __init__(self, x_increment: int, y_increment: int, map_file: str = "input.txt", starting_x: int = 0, starting_y: int = 0): self.x_increment = x_increment self.y_increment = y_increment self.map = utils.read_input_file(filename=map_file) self.repeat = len(self.map[0]) - 1 self.current_x = starting_x self.current_y = starting_y self.trees_encountered = 0
def main(): grouped_answers = utils.read_input_file( "customs_declaration_form_questions.txt") print(f"grouped_answers = {grouped_answers}") sum_of_counts = 0 sets_of_answers = [[{x for x in y} for y in z if y] for z in grouped_answers] for set_of_answers in sets_of_answers: combined_answers = set_of_answers.pop() for answer in set_of_answers: combined_answers.intersection_update(answer) sum_of_counts += len(combined_answers) print(f"Sum of counts: {sum_of_counts}")
def createModelFilesFromInput(input_filename, q_mle_filename, e_mle_filename): logging.basicConfig() log = logging.getLogger() log.setLevel(logging.DEBUG) log.debug("Reading input file") train_data = utils.read_input_file(input_filename, replace_numbers=False) log.debug("- Converting words\\tags to ids") W2I = list_to_ids(flatten(reduce_tuple_list(train_data, dim=0)), MIN_COUNT=COMMON_WORD_MIN_COUNT) #Unknown words unk_words = MLETrain.__generate_unk_words() i = max(W2I.values()) + 1 for w_unk in unk_words: W2I[w_unk] = i i += 1 T2I = list_to_ids(flatten(reduce_tuple_list(train_data, dim=1))) train_data_ids = MLETrain.__sentences_to_ids(train_data, W2I, T2I) # Inverse dictionary I2T = utils.inverse_dict(T2I) I2W = utils.inverse_dict(W2I) log.debug("- Counting:") count_tag_triplets = Counter() count_tag_pairs = Counter() count_tag_single = Counter() count_word_tags = Counter() count_word_tags.update() for sentence in train_data_ids: words_ids = sentence[0] tags_ids = sentence[1] # Q count_tag_triplets.update(utils.count_triplets(tags_ids)) count_tag_pairs.update(utils.count_pairs(tags_ids)) count_tag_single.update(utils.count_single(tags_ids)) # E count_word_tags.update(utils.count_word_tags(words_ids, tags_ids)) log.debug("Writing to file {}".format(q_mle_filename)) utils.write_q_mle_file(count_tag_triplets, count_tag_pairs, count_tag_single, I2T, q_mle_filename) log.debug("Writing to file {}".format(e_mle_filename)) utils.write_e_mle_file(count_word_tags, I2T, I2W, e_mle_filename) log.debug("Done")
def __init__(self, filenames): """Initialize the simulation case. Read the SENKIN-format input file is read into the ``keywords`` dictionary. :param filenames: Dictionary containing the relevant file names for this case. """ self.input_filename = filenames['input_filename'] self.mech_filename = filenames['mech_filename'] self.save_filename = filenames['save_filename'] self.thermo_filename = filenames['thermo_filename'] self.keywords = utils.read_input_file(self.input_filename)
def main(): instructions = utils.read_input_file("code_instructions.txt") acc = 0 index = 0 visited = set() while index not in visited: visited.add(index) op, value = instructions[index].split(" ") print(f"Index: {index}\tOp: {op}\tValue: {value}") if op == "jmp": index += int(value.strip()) continue if op == "acc": acc += int(value.strip()) index += 1 if index in visited: print(f"Exiting early...") print(f"Acc = {acc}")
def main(): seat_ids = list() for boarding_pass in utils.read_input_file("boarding_passes.txt"): plane_length = BspTree(length=128, upper_indicator="B", lower_indicator="F") row = plane_length.find_node(boarding_pass[:7]) plane_width = BspTree(length=8, upper_indicator="R", lower_indicator="L") column = plane_width.find_node(boarding_pass[7:]) # print(f"'FBFBBFFRLR' represents seat: row {row}, column {column}") seat_id = row * 8 + column print(f"Seat id: {seat_id}") seat_ids.append(seat_id) for x in range(sorted(seat_ids)[0], sorted(seat_ids)[-1]): if x not in seat_ids: print(f"Missing seat id: {x}") print(f"Highest seat id: {sorted(seat_ids)[-1]}") print(f"Lowest seat id: {sorted(seat_ids)[0]}")
def get_data() -> np.ndarray: return utils.read_input_file()
import utils def characters_are_the_same(first_character, second_character): return first_character == second_character input_values_from_file = utils.read_input_file(filename="input.txt") input_values = [x.strip().split(" ") for x in input_values_from_file] things_to_test = [{ "first_occurence": int(x[0].split("-")[0]) - 1, "second_occurence": int(x[0].split("-")[1]) - 1, "character": x[1][0], "password": x[2] } for x in input_values] valid_passwords = 0 for thing in things_to_test: if characters_are_the_same(thing['character'], thing['password'][ thing['first_occurence']]) ^ characters_are_the_same( thing['character'], thing['password'][thing['second_occurence']]): valid_passwords += 1 else: print(f"Password {thing['password']} does not meet password policy") print(f"Number of valid passwords: {valid_passwords}")
from itertools import product import utils sum_total = 2020 input_values_from_file = utils.read_input_file() input_values = utils.convert_elements_in_list_to_integers( input_values_from_file) for values in product(input_values, input_values, input_values): if sum(list(values)) == sum_total: print(values) print( f"The product of the values is: {values[0] * values[1] * values[2]}" )
import sys import utils TREE_MAP = utils.read_input_file(filename="input.txt") X_INCREMENT = 1 Y_INCREMENT = 3 def is_a_tree(x, y): return TREE_MAP[x][y % (len(TREE_MAP[0]) - 1)] == "#" def next_location(x, y): return x + X_INCREMENT, y + Y_INCREMENT def main(current_x: int = 0, current_y: int = 0) -> int: trees_encountered = 0 for row in TREE_MAP: if is_a_tree(current_x, current_y): trees_encountered += 1 current_x, current_y = next_location(current_x, current_y) print(f"Number of trees encountered: {trees_encountered}") return if __name__ == "__main__": try: start_x = sys.argv[1] except IndexError:
import utils as utils if __name__ == '__main__': nodes, edges = utils.read_input_file('input.txt') utils.verify_edge_numbers(nodes, edges) graph = utils.create_graph(nodes, edges) utils.save_graph_to_file(graph, "graph.png") utils.can_be_two_cliques(graph)
import sys import time from utils import read_input_file, dynamic_programming_solution, write_output_file, numba_solution try: _, alg, input_file_path, output_file_path = sys.argv if alg not in ('standart', 'numba'): raise ValueError except ValueError: print( 'Incorrect parameters, use: [algorithm (standart / numba)] [input file] [output file]' ) sys.exit() start_time = time.time() investor, bonds = read_input_file(input_file_path, alg) if alg == 'standart': bonds_list = dynamic_programming_solution(investor, bonds) elif alg == 'numba': bonds_list = numba_solution(investor, bonds) else: raise ValueError write_output_file(output_file_path, investor, bonds_list) duration = time.time() - start_time print('Duration is {:.2f} ms'.format(duration * 1000))
def read_input_data(filename="input00.txt"): result_list = read_input_file(filename) for line in result_list: yield int(line.strip("\n"))
def read_input_data(): result_list = read_input_file() return result_list[0].strip("\n"), list(map(int, result_list[1].split()))
def main(): data = utils.read_input_file(to_array).transpose() gamma, epsilon = read_report(data) print( "The gamma rate is {}, epsilon rate is {}. The power consumption is {}" .format(gamma, epsilon, gamma * epsilon))
def main(): submarine = Position() commands = utils.read_input_file(parse_commands) get_final_destination(submarine, commands) print("The final horizontal position by the final depth is: {}".format(submarine.HPos * submarine.Depth))
def get_data() -> np.ndarray: return utils.read_input_file(pre_process_data)
while index not in visited: visited.add(index) op, value = instructions[index].split(" ") if op == "acc": acc += int(value.strip()) if op == "jmp": index += int(value.strip()) else: index += 1 if index > len(instructions) - 1: finished = True break return finished, acc if __name__ == "__main__": instructions = utils.read_input_file("code_instructions.txt") for index, instruction in enumerate(instructions): op, value = instruction.split(" ") if op == "acc": continue copy = instructions[:] if op == "jmp": copy[index] = copy[index].replace("jmp", "nop") if op == "nop": copy[index] = copy[index].replace("nop", "jmp") finished, acc = main(copy) if finished: print(acc) exit()
if __name__ == '__main__': args = sys.argv[1:] if len(args) != 4: print "Wrong number of arguments. Use:\n" + \ "python GreedyMaxEntTag.py input_file model_file output_file feature_map_file" exit() input_filename = args[0] model_filename = args[1] output_filename = args[2] feature_map_filename = args[3] logreg = joblib.load(model_filename) sentences = utils.read_input_file(input_filename, replace_numbers=False) feature_map_dict = memm_utils.feature_map_file_to_dict( feature_map_filename) T2I, feature_map_dict_vect = memm_utils.feature_dict_to_dict_vectorizer( feature_map_dict) common_words, tags = memm_utils.words_and_tags_from_map_dict( feature_map_dict) model = joblib.load(model_filename) tagger = GreedyTag(model, feature_map_dict_vect, T2I, common_words) # Run tagger and write prediction to file utils.predict_and_write_to_file(sentences, output_filename, tagger.getPrediction)
label = features.pop('t_i') # Remove label from feature vec line = label + ' ' + ' '.join(['{}={}'.format(k,v) for k,v in features.iteritems()]) + '\n' f.write(line) if __name__ == '__main__': args = sys.argv[1:] if len(args) != 2: print "Wrong number of arguments. Use:\n" + \ "python ExtractFeature.py corpus_file feature_filename" exit() corpus_filename = args[0] feature_filename = args[1] train_data = utils.read_input_file(corpus_filename, replace_numbers=False) W2I = list_to_ids(flatten(reduce_tuple_list(train_data, dim=0)), MIN_COUNT=COMMON_WORD_MIN_COUNT) try: with open(feature_filename, "w+") as f: sentences_count = len(train_data) done_count = 0 progress = None for words, tags in train_data: featuresList = extract_features(words, tags, W2I) writeFeaturesListToFile(featuresList, f) done_count += 1 progress = utils.progress_hook(done_count, sentences_count, progress) except Exception: raise
def main(bag_colour: str): rules = utils.read_input_file("baggage_rules.txt") print(len(bags_that_can_hold_bags(bag_colour, rules)))
def get_data() -> defaultdict: data = utils.read_input_file(pre_process_data) return build_map(data)