def __attrs_post_init__(self) -> None: if quantify(self.all_axes) != 3: raise RuntimeError(f"All objects must have three axes but got {self}") num_gravitationally_aligned_axes = quantify( x.aligned_to_gravitational for x in chain((self.primary_axis,), self.orienting_axes) ) if num_gravitationally_aligned_axes > 1: raise RuntimeError( f"A Geon cannot have multiple gravitationally aligned axes: {self}" )
def solver(): with open('input.txt', 'r') as f: seats = [list(x) for x in f.read().strip().splitlines()] end_state = simulate(seats) print('Part 1:', quantify(flatten(end_state), lambda x: x == OCCUPIED)) # 2277 end_state = simulate(seats, occupied_threshold=5, neighbours_fn=all_visible) print('Part 2:', quantify(flatten(end_state), lambda x: x == OCCUPIED)) # 2066
def _some_object_has_binary_property( perception_frame: DevelopmentalPrimitivePerceptionFrame, query_property: OntologyNode) -> bool: return (quantify( isinstance(property_assertion, HasBinaryProperty) and property_assertion.binary_property == query_property for property_assertion in perception_frame.property_assertions) > 0)
def num_occupied(lines, empty_to_occupied, occupied_to_empty): layout = [list(line.strip()) for line in lines] has_changed = True acc = 0 while has_changed: acc += 1 has_changed = False new_layout = [] for i, row in enumerate(layout): new_row = [] for j, seat in enumerate(row): update = None if seat == FLOOR: pass elif seat == EMPTY and empty_to_occupied(i, j, layout): update = OCCUPIED elif seat == OCCUPIED and occupied_to_empty(i, j, layout): update = EMPTY new_row.append(update or seat) if update: has_changed = True new_layout.append(new_row) layout = new_layout log.info("Iterations: %s", acc) log.info("Layout: %s", layout) return quantify(flatten(layout), lambda x: x == OCCUPIED)
def _calc_unstalled(instructions: Iterable[InstrState]) -> int: """Count the number of unstalled instructions. `instructions` are the list of instructions to count unstalled ones in. """ return more_itertools.quantify( instructions, lambda instr: instr.stalled == StallState.NO_STALL)
def api_achievement_scores(world: minecraft.World): """Returns an object mapping player's IDs to their current score in the achievement run.""" return { player_id: more_itertools.quantify( (value['value'] if isinstance(value, dict) else value) > 0 for value in achievement_data.values()) for player_id, achievement_data in api_playerstats_achievements( world).items() }
def get_closest_coords(arguments, biomes, start_x, start_z): chunks_by_distance = list( all_chunks_sorted_by_distance(arguments, start_x, start_z)) result = { biome: { 'x': None, 'z': None, 'found_chunk_distance': None } for biome in biomes } for i, (chunk_distance, chunk) in enumerate(chunks_by_distance): if arguments['--verbose']: progress = min(4, int(5 * i / len(chunks_by_distance))) print( '[{}{}] {} out of {} chunks checked, {} out of {} biomes found' .format( '=' * progress, '.' * (4 - progress), i, len(chunks_by_distance), more_itertools.quantify( biome_info['found_chunk_distance'] is not None for biome_info in result.values()), len(result)), end='\r', flush=True) if all(biome_result['found_chunk_distance'] is not None and chunk_distance > biome_result['found_chunk_distance'] + 3 for biome_result in result.values()): break # if the chunk distance is 4 more than the last found, the block distance cannot be smaller while True: try: chunk_data = api_json( arguments, '/v2/world/{{world}}/chunks/overworld/chunk/{}/0/{}.json'. format(chunk['x'], chunk['z'])) except requests.RequestException: continue break for row in chunk_data[0]: for block in row: biome = Biome[block['biome']] if biome in result: if result[biome]['found_chunk_distance'] is None or abs( block['x'] - start_x) + abs(block['z'] - start_z) < abs( result[biome]['x'] - start_x) + abs(result[biome]['z'] - start_z): result[biome] = { 'found_chunk_distance': chunk_distance, 'x': block['x'], 'z': block['z'] } if arguments['--verbose']: print('[ ok ]') return result
def pprint_cmp(result, as_rate=None): """Pretty print a result from timethese Parameters ---------- result a result from timethese as_rate If None, the display format is determined automatically. If True, a rate is shown as function performance (unit 1/s), if False, the time is shown (unit s) Returns ------- dict a string table with the results """ if as_rate is None: # determine rate display automatically big_rates_count = quantify(result["times"], lambda t: t < 1) as_rate = result and big_rates_count / len(result["times"]) > 0.5 perf = result["rates"] if as_rate else result["times"] perf = [_format_perf(p, as_rate) for p in perf] names = result["names"] top_row = ["", "Rate" if as_rate else "s/iter", *names] rows = [top_row] + [list(x) for x in zip(names, perf)] col_widths = [len(x) for x in top_row] col_widths[0] = max([len(n) for n in names]) col_widths[1] = max([len(rows[i][1]) for i in range(len(rows))]) for ridx, r in enumerate(result["data"]): for cidx, c in enumerate(r): if ridx == cidx: val = "." else: val = "{:.0f}%".format(c * 100) rows[ridx + 1].append(val) if len(val) > col_widths[cidx + 2]: col_widths[cidx + 2] = len(val) def format_row(row, widths): return " ".join( ["{:>{fill}s}".format(x[0], fill=x[1]) for x in zip(row, widths)]) return "\n".join([format_row(r, col_widths) for r in rows])
def flip(start_floor: TFloor, days=100) -> TFloor: current_floor = start_floor for _ in range(days): current_floor = add_neighbors(current_floor) next_floor = current_floor.copy() for tile, is_black in current_floor.items(): black_neighbors = quantify(current_floor[n] for n in all_neighbors(tile) if n in current_floor) if is_black and black_neighbors not in [1, 2]: next_floor[tile] = False elif not is_black and black_neighbors == 2: next_floor[tile] = True current_floor = next_floor return current_floor
def test_happy_path(self): """Make sure True count is returned""" q = [True, False, True] self.assertEqual(mi.quantify(q), 2)
def solve_part2(file_name): return quantify(read_line_separated_list(file_name), pred=_is_valid_password2)
def test_custom_predicate(self): """Ensure non-default predicates return as expected""" q = range(10) self.assertEqual(mi.quantify(q, lambda x: x % 2 == 0), 5)
def count_steps(step_list, step_size): return quantify(step_list, lambda step: step == step_size)
def test_potential_message_targets(self): targets = list(potential_message_targets()) # Two targets for participant 1: three children for both studies. These # will be weeded out downstream, as they all fail to meet criteria in one way # or another. self.assertEqual( quantify(mt.user_id == self.participant_one.id for mt in targets), 6, ) # Participant #2 # Child 2 should only receive a single message for study 2, since they completed # the consent frame for study 1 self.assertNotIn( MessageTarget( user_id=self.participant_two.id, child_id=self.child_two.id, study_id=self.study_one.id, ), targets, ) self.assertIn( MessageTarget( user_id=self.participant_two.id, child_id=self.child_two.id, study_id=self.study_two.id, ), targets, ) # Child 3 should receive a message for both studies. self.assertIn( MessageTarget( user_id=self.participant_two.id, child_id=self.child_three.id, study_id=self.study_one.id, ), targets, ) self.assertIn( MessageTarget( user_id=self.participant_two.id, child_id=self.child_three.id, study_id=self.study_two.id, ), targets, ) # Sanity check - participant #2 isn't suddenly the parent of child #1... self.assertFalse( any( mt.user_id == self.participant_two.id and mt.child_id == self.child_one.id for mt in targets ) ) # Check other way around as well self.assertFalse( any( mt.user_id == self.participant_one.id and mt.child_id in (self.child_two.id, self.child_three.id) for mt in targets ) )
def count_active(cube: TCube) -> int: return quantify(cube.values(), lambda x: x == ACTIVE)
def num_chars(s, char): return quantify(s, lambda c: c == char)
def test_same_zero_count(xs): before_zeroes = quantify(xs, lambda x: x == 0) after = move_zeroes(xs) after_zeroes = quantify(after, lambda x: x == 0) assert before_zeroes == after_zeroes
def number_of_occupied_adjacent_seats(cls, grid, x, y): return quantify(cls.adjacent_seats(grid, x, y), lambda c: grid.at(*c) == "#")
def count_blacks(floor: TFloor) -> int: return quantify(floor.values())
def score(order: typ.Iterable[Station], compare_to: typ.Iterable[Station]) -> int: idx = {station: i for i, station in enumerate(order)} return quantify(idx[s1] < idx[s2] for s1, s2 in pairwise(compare_to))
def _init_num_slots(self) -> int: return quantify(element for element in self.elements if isinstance(element, SyntaxSemanticsVariable))
def api_achievement_scores(world: minecraft.World): """Returns an object mapping player's IDs to their current score in the achievement run.""" return {player_id: more_itertools.quantify((value['value'] if isinstance(value, dict) else value) > 0 for value in achievement_data.values()) for player_id, achievement_data in api_playerstats_achievements(world).items()}
def solve_part2(file_name): passports = read(file_name).split("\n\n") return quantify(map(_parse_passport, passports), pred=partial(_validate_with_model, PassportB))
# I use a list comprehension and store of all values=[True\False] from key='isActive'. is_active = [status['isActive'] for status in profiles_json] # I use a list comprehension to store only False values using key='isActive' # I stored active\inactive users differently so I could practice using # the more_itertools module. is_inactive = [ status['isActive'] for status in profiles_json if (status['isActive'] != True) ] # These two functions are from the more_itertools module. # more_itertools.quantify returns a single numeric value for all instances of bool->True # The value returned is of type int is_active_count = more_itertools.quantify(is_active) # more_itertools.ilen returns the length of the iterator. # `is_inactive` contains only False values. Like more_itertools.quantify # more_itertools.ilen returns a single numeric value of type int is_inactive_count = more_itertools.ilen(is_inactive) print(f"Number of active users: {is_active_count}") print(f"Number of inactive users {is_inactive_count}") # > Grand total of all balance for all users # In[339]: # I use a list comprehension to 'pluck out' values from each user using key='balance' # Once I get that value, I need to remove the $ and , characters using regex.