def check(put: unittest.TestCase, arrangement: Arrangement, expectation: Expectation): actor = ActorThatRecordsSteps( arrangement.test_case_generator.recorder, arrangement.actor) def action(std_files: StdOutputFiles) -> PartialExeResult: exe_conf = ExecutionConfiguration(dict(os.environ), DEFAULT_ATC_OS_PROCESS_EXECUTOR, sandbox_root_name_resolver.for_test(), exe_atc_and_skip_assertions=std_files) with home_directory_structure() as hds: conf_phase_values = ConfPhaseValues(actor, hds, timeout_in_seconds=arrangement.timeout_in_seconds) return sut.execute(arrangement.test_case_generator.test_case, exe_conf, conf_phase_values, setup.default_settings(), False, ) out_files, partial_result = capture_stdout_err(action) expectation.result.apply_with_message(put, partial_result, 'partial result') put.assertEqual(expectation.step_recordings, arrangement.test_case_generator.recorder.recorded_elements, 'steps') expectation.atc_stdout_output.apply_with_message(put, out_files.out, 'stdout') expectation.atc_stderr_output.apply_with_message(put, out_files.err, 'stderr')
def check(self, tc, exp_log, cachedMsg): exp_level, exp_msgs = exp_log act_msgs = cachedMsg[1:] if exp_level is 'INFO': TestCase.assertEqual(tc, exp_msgs, act_msgs) if exp_level is 'ERROR': pass #
def _check_existence(self, put: unittest.TestCase, actual: DirDependentValue, message_builder: asrt.MessageBuilder): put.assertEqual(self._expected.exists_pre_sds(), actual.exists_pre_sds(), message_builder.apply('exists_pre_sds'))
def _apply(self, put: unittest.TestCase, value, message_builder: asrt.MessageBuilder): put.assertIsInstance(value, rs.SymbolTable) assert isinstance(value, rs.SymbolTable) put.assertEqual(self.expected.names_set, value.names_set, message_builder.apply('names in symbol table')) for name in self.expected.names_set: actual_value = value.lookup(name) put.assertIsInstance(actual_value, rs.SymbolContainer, message_builder.apply('actual container for ' + name)) assert isinstance(actual_value, rs.SymbolContainer) expected_container = self.expected.lookup(name) put.assertIsInstance(expected_container, rs.SymbolContainer, message_builder.apply('expected container for ' + name)) assert isinstance(expected_container, rs.SymbolContainer) equals_container(expected_container).apply(put, actual_value, message_builder.for_sub_component('Value of symbol ' + name))
def _apply(self, put: unittest.TestCase, value: T, message_builder: MessageBuilder): put.assertEqual(self.expected, value, message_builder.apply(self.message))
def _apply(self, put: unittest.TestCase, value: Sized, message_builder: MessageBuilder): put.assertEqual(self.expected, len(value), message_builder.for_sub_component('length').apply(self.message))
def _assert_table_contains_single_value(put: unittest.TestCase, table: sut.SymbolTable, expected_symbol: NameAndValue): _assert_table_contains(put, table, expected_symbol) put.assertEqual({expected_symbol.name}, table.names_set, 'names set should contain a single value')
def get_printed_sds_or_fail(put: unittest.TestCase, actual: SubProcessResult) -> str: printed_lines = actual.stdout.splitlines() put.assertEqual(1, len(printed_lines), 'Number of printed printed lines should be exactly 1') actual_sds_directory = printed_lines[0] return actual_sds_directory
def _check_sub_class_properties(self, put: unittest.TestCase, actual: DirDependentValue, tcds: HomeAndSds, message_builder: asrt.MessageBuilder): put.assertIsInstance(actual, SingleDirDependentValue, message_builder.apply('class')) assert isinstance(actual, SingleDirDependentValue) # Type info for IDE put.assertEqual(self._resolving_dependency, actual.resolving_dependency(), message_builder.apply('resolving_dependency')) assertion_on_resolved_value = self.resolved_value(tcds) if not self._resolving_dependency or self._resolving_dependency == DirectoryStructurePartition.HOME: resolved_value_post_sds = actual.value_pre_sds(tcds.hds) assertion_on_resolved_value.apply(put, resolved_value_post_sds, message_builder.for_sub_component('value_pre_sds')) if not self._resolving_dependency or self._resolving_dependency == DirectoryStructurePartition.NON_HOME: resolved_value_post_sds = actual.value_post_sds(tcds.sds) assertion_on_resolved_value.apply(put, resolved_value_post_sds, message_builder.for_sub_component('value_pre_sds'))
def test_enumJointLabelings(self): #print nx.maximal_matching(self.graph) #print nx.max_weight_matching(self.graph) joint,first = SR.enumJointLabelings([self.graph]) TestCase.assertEqual(self,len(joint[self.graph]),15) valid, validAtNode = SR.validLabels(joint,first) TestCase.assertEqual(self,len(valid[self.graph]),8)
def assertions(self, put: unittest.TestCase, reporter: ExecutionTracingRootSuiteReporter, actual_exit_code: int): put.assertEqual(ExecutionTracingRootSuiteReporter.VALID_SUITE_EXIT_CODE, actual_exit_code, 'Expecting the suite be be valid (and thus to have been executed).') _assert_every_test_case_to_pass(put, reporter)
def _apply(self, put: unittest.TestCase, value, message_builder: asrt.MessageBuilder): put.assertIsInstance(value, spe.ResultAndStderr) put.assertEqual(self.stderr_contents, value.stderr_contents, message_builder.apply('Stderr contents'))
def _apply(self, put: unittest.TestCase, value, message_builder: asrt.MessageBuilder): put.assertIsInstance(value, spe.ResultAndStderr) put.assertEqual(self.exit_code, value.result.exit_code, message_builder.apply('Exit code'))
def _apply(self, put: unittest.TestCase, value: StringTransformerModel, message_builder: MessageBuilder): actual = len(list(value)) put.assertEqual(self.expected_num_lines, actual, 'number of lines')
def assert_coordinate_lists_equal(coordinate_list: List[Coordinate], expected_coordinate_list: List[Coordinate], test_case: TestCase): test_case.assertEqual(len(list(coordinate_list)), len(list(expected_coordinate_list))) for coordinate, expected_coordinate in zip(coordinate_list, expected_coordinate_list): assert_coordinates_equal(coordinate=coordinate, expected_coordinate=expected_coordinate, test_case=test_case)
def _apply(self, put: unittest.TestCase, value: HomeAndSds, message_builder: asrt.MessageBuilder): relativity_root = REL_OPTIONS_MAP[self.relativity].root_resolver.from_home_and_sds(value) put.assertEqual(relativity_root / self.expected_sub_dir_of_act_dir, pathlib.Path.cwd(), message_builder.apply('CWD expected to be sub-dir of ' + str(self.relativity)))
def _apply(self, put: unittest.TestCase, value: Result, message_builder: asrt.MessageBuilder): msg = 'set of phases that have the environment variable in the global environment is expected to be empty' put.assertEqual(set(), self.phases_that_contains_the_environment_variable, msg)
def _check_custom_dependencies(self, put: unittest.TestCase, actual: MultiDirDependentValue, home_and_sds: HomeAndSds, message_builder: asrt.MessageBuilder): put.assertEqual(self._expected_multi_dep_value.dir_dependencies(), actual.dir_dependencies(), message_builder.apply('dir_dependency'))
def _check_indent(put: unittest.TestCase, wrapper: sut.Wrapper, expected_current_indent: sut.Indent, expected_saved_stack: list): _check_current_indent(put, wrapper, expected_current_indent) put.assertEqual(expected_saved_stack, wrapper.saved_indents_stack, 'Saved indent stack')
def _check_custom_dependencies(self, put: unittest.TestCase, actual: SingleDirDependentValue, home_and_sds: HomeAndSds, message_builder: asrt.MessageBuilder): put.assertEqual(self._expected_single_dep_value.resolving_dependency(), actual.resolving_dependency(), message_builder.apply('resolving_dependency'))
def test_encoding_one_value(self): """ Test that one integer encoded correctly with different bit_count value """ for i in range(1, 9): data = bytearray(b'\x00\x00\x00\x00\x00\x00\x00\x00') _encode_to_byte(self.value, i, 8, data) TestCase.assertEqual(self, data, self.res_data[i])
def test_tmx_stackCollisionEvents(self): walls = self.game.tilemap.layers['walls'] destination = walls.cells[walls.cells.keys()[0]] (dx, dy) = self.__calcule_delta(self.game.perso, destination) self.game.perso.move(dx, dy) TestCase.assertEqual(self, len(self.game.tmxEvents), 0) self.game.tmx_stackCollisionEvents(self.game.perso, self.game.tmxEvents) TestCase.assertGreater(self, len(self.game.tmxEvents), 0)
def assert_equal_lines(unit_tc: unittest.TestCase, expected: line_source.Line, actual: line_source.Line): unit_tc.assertEqual(expected.line_number, actual.line_number, 'Source line number') unit_tc.assertEqual(expected.text, actual.text, 'Source text')
def _check_common_dependencies(self, put: unittest.TestCase, actual: DirDependentValue, message_builder: asrt.MessageBuilder): put.assertEqual(self._expected.has_dir_dependency(), actual.has_dir_dependency(), message_builder.apply('has_dir_dependency')) put.assertEqual(self._expected.resolving_dependencies(), actual.resolving_dependencies(), message_builder.apply('resolving_dependencies'))
def assert_contents_and_that_last_child_is_returned( expected_xml: str, root: Element, ret_val_from_renderer: Element, put: unittest.TestCase): xml_string = as_unicode_str(root) put.assertEqual(expected_xml, xml_string) put.assertIs(list(root)[-1], ret_val_from_renderer)
def check_exit_code_and_empty_stdout(put: unittest.TestCase, expected_exit_code: int, actual_exit_code: int, str_std_out_files: StringStdOutFiles): str_std_out_files.finish() put.assertEqual(expected_exit_code, actual_exit_code, 'Exit code') put.assertEqual('', str_std_out_files.stdout_contents, 'Output to stdout')
def check_list(put: unittest.TestCase, expected: list, actual: ExecutionTracingRootSuiteReporter): """ :param expected: [ExpectedSuiteReporting] """ for i, (e, a) in enumerate(zip(expected, actual.sub_suite_reporters)): e.check(put, a, 'Suite at index ' + str(i) + ': ') put.assertEqual(len(expected), len(actual.sub_suite_reporters), 'Number of suites')
def check_exception(self, root_path: pathlib.Path, actual: Exception, put: unittest.TestCase): put.assertIsInstance(actual, SuiteParseError) put.assertEqual(str(self.root_suite_based_at(root_path)), str(actual.suite_file), 'Source file that contains the error') assert_equals_line_sequence(put, single_line_sequence(1, '"starting but no closing double quote'), actual.source)
def check_exception(self, root_path: pathlib.Path, actual: Exception, put: unittest.TestCase): put.assertIsInstance(actual, SuiteFileReferenceError) put.assertEqual(str(self.root_suite_based_at(root_path)), str(actual.suite_file), 'Source file that contains the error') assert_equals_line_sequence(put, single_line_sequence(2, 'does-not_exist.suite'), actual.source)
def assert_is_success_and_output_dir_contains_at_least_result_files(put: unittest.TestCase, expected: SubProcessResult, actual: sut.Result): put.assertTrue(actual.is_success, 'Result should indicate success') put.assertEqual(expected.exitcode, actual.exit_code, 'Exit code') contents_assertion = assert_dir_contains_at_least_result_files(PROCESS_OUTPUT_WITH_NON_ZERO_EXIT_STATUS, actual.file_names) contents_assertion.apply(put, actual.output_dir_path)
s += 'r' else: s += '-' if n & w > 0: s += 'w' else: s += '-' if n & x > 0: s += 'x' else: s += '-' return s def w5d4(rwx): strOwner = toRwxString(rwx[0]) strGroup = toRwxString(rwx[1]) strOther = toRwxString(rwx[2]) # print(strOwner, strGroup, strOther) return '{:03b} {:03b} {:03b} and {:s} {:s} {:s}'.format(rwx[0], rwx[1], rwx[2], strOwner, strGroup, strOther) t = TestCase() t.assertEqual('001 000 100 and --x --- r--', w5d4([1, 0, 4])) t.assertEqual('111 111 010 and rwx rwx -w-', w5d4([7, 7, 2])) t.assertEqual('110 011 101 and rw- -wx r-x', w5d4([6, 3, 5])) t.assertEqual('000 010 110 and --- -w- rw-', w5d4([0, 2, 6])) t.assertEqual('101 010 111 and r-x -w- rwx', w5d4([5, 2, 7])) print('OK!')
# https://www.codewars.com/kata/number-of-trailing-zeros-of-n/train/python from unittest import TestCase from math import log def zeros(n): if n < 1: return 0 upper = int(log(n, 5)) powers = range(upper, 0, -1) return sum(list(map(lambda x: n // (5**x), powers))) test = TestCase() test.assertEqual(zeros(6), 1) test.assertEqual(zeros(12), 2) test.assertEqual(zeros(19), 3) test.assertEqual(zeros(26), 6) test.assertEqual(zeros(30), 7) test.assertEqual(zeros(100), 24)
def assert_standard_pos(test: unittest.TestCase, myPos: Position): test.assertEqual(myPos.x, 500) test.assertEqual(myPos.y, 0) test.assertEqual(myPos.z, -46.3) test.assertEqual(myPos.A, 0.01) test.assertEqual(myPos.B, -179.99) test.assertEqual(myPos.arg1, "R") test.assertEqual(myPos.arg2, "A") test.assertEqual(myPos.grip, "C")
def middleNode(head: ListNode) -> ListNode: pSlow = pFast = head while pFast.next is not None and pFast.next.next is not None: pSlow = pSlow.next pFast = pFast.next.next if pFast.next is None: return pSlow return pSlow.next if __name__ == "__main__": l1 = ListNode(1) l2 = ListNode(2) l3 = ListNode(3) l4 = ListNode(4) l5 = ListNode(5) l6 = ListNode(6) l1.next = l2 l2.next = l3 l3.next = l4 l4.next = l5 l5.next = l6 test = TestCase() test.assertEqual(4, middleNode(l1).val)
def test_queue_implementation_2(): tc = TestCase() q = Queue(10) for i in range(6): q.enqueue(i) tc.assertEqual(q.data.count(None), 4) for i in range(5): q.dequeue() tc.assertFalse(q.empty()) tc.assertEqual(q.data.count(None), 9) tc.assertEqual(q.head, q.tail) tc.assertEqual(q.head, 5) for i in range(9): q.enqueue(i) with tc.assertRaises(RuntimeError): q.enqueue(10) for x, y in zip(q, [5] + list(range(9))): tc.assertEqual(x, y) tc.assertEqual(q.dequeue(), 5) for i in range(9): tc.assertEqual(q.dequeue(), i) tc.assertTrue(q.empty())
def test_bulk_operations(): say_test("test_bulk_operations") tc = TestCase() lst = LinkedList() lst2 = LinkedList() lst3 = lst + lst2 tc.assertIsInstance(lst3, LinkedList) tc.assertEqual(0, len(lst3)) import random data = [random.randrange(1000) for _ in range(50)] data2 = [random.randrange(1000) for _ in range(50)] for d in data: lst.append(d) for d in data2: lst2.append(d) lst3 = lst + lst2 tc.assertEqual(100, len(lst3)) data3 = data + data2 for i in range(len(data3)): tc.assertEqual(data3[i], lst3[i]) lst.clear() tc.assertEqual(0, len(lst)) with tc.assertRaises(IndexError): lst[0] for d in data: lst.append(d) lst2 = lst.copy() tc.assertIsNot(lst, lst2) tc.assertIsNot(lst.head.next, lst2.head.next) for i in range(len(data)): tc.assertEqual(lst[i], lst2[i]) tc.assertEqual(lst, lst2) lst.clear() lst.extend(range(10)) lst.extend(range(10,0,-1)) lst.extend(data.copy()) tc.assertEqual(70, len(lst)) data = list(range(10)) + list(range(10, 0, -1)) + data for i in range(len(data)): tc.assertEqual(data[i], lst[i])
def test_case_5(): test_log("testing queries") # (10 points) test queries tc = TestCase() lst = ArrayList() tc.assertEqual(0, len(lst)) tc.assertEqual(0, lst.count(1)) with tc.assertRaises(ValueError): lst.index(1) import random data = [random.randrange(1000) for _ in range(100)] lst.data = ConstrainedList.create(data) lst.len = len(lst.data) tc.assertEqual(100, len(lst)) tc.assertEqual(min(data), lst.min()) tc.assertEqual(max(data), lst.max()) for x in data: tc.assertEqual(data.index(x), lst.index(x)) tc.assertEqual(data.count(x), lst.count(x)) with tc.assertRaises(ValueError): lst.index(1000) lst.data = ConstrainedList.create([1, 2, 1, 2, 1, 1, 1, 2, 1]) lst.len = len(lst.data) tc.assertEqual(1, lst.index(2)) tc.assertEqual(1, lst.index(2, 1)) tc.assertEqual(3, lst.index(2, 2)) tc.assertEqual(7, lst.index(2, 4)) tc.assertEqual(7, lst.index(2, 4, -1)) with tc.assertRaises(ValueError): lst.index(2, 4, -2) suc()
def verify(t: unittest.TestCase, run: kfp_server_api.ApiRun, tasks: dict[str, KfpTask], **kwargs): t.assertEqual(run.status, 'Succeeded') t.assertCountEqual(['importer', 'train'], tasks.keys(), 'task names') importer = tasks['importer'] train = tasks['train'] t.assertEqual( 'gs://ml-pipeline-playground/shakespeare1.txt', importer.outputs.artifacts[0].uri, 'output artifact uri of importer should be "gs://ml-pipeline-playground/shakespeare1.txt"' ) t.assertEqual( 'gs://ml-pipeline-playground/shakespeare1.txt', train.inputs.artifacts[0].uri, 'input artifact uri of train should be "gs://ml-pipeline-playground/shakespeare1.txt"' ) importer_dict = importer.get_dict() train_dict = train.get_dict() for artifact in importer_dict.get('outputs').get('artifacts'): # pop metadata here because the artifact which got re-imported may have metadata with uncertain data if artifact.get('metadata') is not None: artifact.pop('metadata') for artifact in train_dict.get('inputs').get('artifacts'): # pop metadata here because the artifact which got re-imported may have metadata with uncertain data if artifact.get('metadata') is not None: artifact.pop('metadata') t.assertEqual( { 'name': 'importer', 'inputs': {}, 'outputs': { 'artifacts': [{ 'name': 'artifact', 'type': 'system.Artifact', # 'type': 'system.Dataset', }], }, 'type': 'system.ImporterExecution', 'state': Execution.State.COMPLETE, }, importer_dict) t.assertEqual( { 'name': 'train', 'inputs': { 'artifacts': [{ 'name': 'dataset', # TODO(chesu): compiled pipeline spec incorrectly sets importer artifact type to system.Artifact, but in the pipeline, it should be system.Dataset. 'type': 'system.Artifact', # 'type': 'system.Dataset' }], }, 'outputs': { 'artifacts': [{ 'metadata': { 'display_name': 'model' }, 'name': 'model', 'type': 'system.Model' }], 'parameters': { 'scalar': '123' } }, 'type': 'system.ContainerExecution', 'state': Execution.State.COMPLETE, }, train_dict)
if not lst: return None m, l, r = 0, 1, 2 # @UnusedVariable root0 = TreeNode(int(lst[m])) lst[0] = root0 for l in range(1, len(lst) - 1, 2): m = (l - 1) // 2 root = lst[m] if (lst[l] is not None): root.left = TreeNode(lst[l]) lst[l] = root.left if (lst[l + 1] is not None): root.right = TreeNode(lst[l + 1]) lst[l + 1] = root.right return root0 if __name__ == '__main__': t = TestCase() t.assertEqual( '{0, l: {1, l: {3, l: {7}, r: {8}}, r: {4, l: {9}, r: {10}}}, r: {2, l: {5}, r: {6}}}', list2tree([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]).print()) t.assertEqual( '{3, l: {5, l: {6}, r: {2, l: {7}, r: {4}}}, r: {1, l: {0}, r: {8}}}', list2tree([3, 5, 1, 6, 2, 0, 8, None, None, 7, 4]).print()) print('OK!')
# In[5]: # (6 points) test subscript-based access from unittest import TestCase import random tc = TestCase() lst = ArrayList() data = [1, 2, 3, 4] lst.data = ConstrainedList(data) for i in range(len(data)): tc.assertEqual(lst[i], data[i]) with tc.assertRaises(IndexError): x = lst[100] with tc.assertRaises(IndexError): lst[100] = 0 with tc.assertRaises(IndexError): del lst[100] lst[1] = data[1] = 20 del data[0] del lst[0] for i in range(len(data)):
if a.val <= b.val: least = a a = a.next else: b = b.next h.next = ListNode(least.val) h = h.next h.next = a if a else b return h0.next if __name__ == '__main__': t = TestCase() s = Solution() # 1 -> 2 # 2 -> 3 a = ListNode(2) a = ListNode(1, a) b = ListNode(3) b = ListNode(2, b) l = s.mergeTwoLists(a, b) t.assertEqual(1, l.val) t.assertEqual(2, l.next.val) t.assertEqual(2, l.next.next.val) t.assertEqual(3, l.next.next.next.val) print('OK!')
def run_rdb_assertions( cls, test_case: unittest.TestCase, retriever: Retriever, definition: specification.ThresholdSpecification ): test_case.assertIsInstance(retriever, threshold.disk.RDBThresholdRetriever) data: pandas.DataFrame = retriever.retrieve() test_case.assertEqual(sorted([column for column in data.keys()]), ['name', 'site_no', 'value']) test_case.assertEqual(len(data.site_no.unique()), 2) test_case.assertEqual(len(data.index.unique()), 366) test_case.assertEqual(data.index.name, 'threshold_day') created_thresholds = threshold.get_thresholds(definition) test_case.assertEqual(len(data.site_no.unique()), len(created_thresholds)) for key, thresholds in created_thresholds.items(): test_case.assertIn(key, data.site_no.unique()) for threshold_name, group_data in data[data.site_no == key].groupby(['name']): matching_thresholds = [ thresh for thresh in thresholds if thresh.name == threshold_name ] test_case.assertEqual(len(matching_thresholds), 1) matching_threshold = matching_thresholds[0] test_case.assertIn(threshold_name, definition) threshold_definition = definition[threshold_name] test_case.assertEqual(threshold_definition.weight, matching_threshold.weight)
def test_parse_rinex_sp3(self): precise = parse_sp3('igs11484.sp3') TestCase.assertEqual(self, len(precise), 28) TestCase.assertEqual(self, precise['G01'][0].date.std.year, 2002)
def check(self, test: unittest.TestCase) -> None: for k, v in self.expectations.items(): test.assertEqual(getattr(self.package, k), v, msg='{} of {}'.format(k, self.package))
def test_stringification(): say_test("test_stringification") tc = TestCase() lst = LinkedList() tc.assertEqual('[]', str(lst)) tc.assertEqual('[]', repr(lst)) lst.append(1) tc.assertEqual('[1]', str(lst)) tc.assertEqual('[1]', repr(lst)) lst = LinkedList() for d in (10, 20, 30, 40, 50): lst.append(d) tc.assertEqual('[10, 20, 30, 40, 50]', str(lst)) tc.assertEqual('[10, 20, 30, 40, 50]', repr(lst))
# 4. For Input Line #4, how many times does the digit 4 appear? for d in lines[3]: if d == '4': answer[3] += 1 # 5. For Input Line #5, what is the middle digit? (If the length of the number, N, is even, # find the N/2 number (again, the leftmost digit is the 1st one). answer[4] = lines[4][ (len(lines[4]) - 1) // 2 ] return answer t = TestCase() reslt = w5d5(['1325678945', '987654', '456160', '143295823976154', '123456']) t.assertEqual(10, reslt[0]) t.assertEqual(39, reslt[1]) t.assertEqual(16, reslt[2]) t.assertEqual(2, reslt[3]) t.assertEqual('3', reslt[4]) reslt = w5d5([ '25370912518369327', '375210958761094', '314159267349087623', '27698136580957210', '3489761230987236580394815']) t = TestCase() t.assertEqual(17, reslt[0]) # how many digits in line 0 t.assertEqual(67, reslt[1]) # sum of all digits t.assertEqual(34, reslt[2]) # how many times of digit 4 t.assertEqual(0, reslt[3]) # sum of digits at odd location - the most significent (leftmost) digit is #1 t.assertEqual('7', reslt[4]) # the middle digit for odd digits number;
def test_queries(): say_test("test_queries") tc = TestCase() lst = LinkedList() tc.assertEqual(0, len(lst)) tc.assertEqual(0, lst.count(1)) with tc.assertRaises(ValueError): lst.index(1) import random data = [random.randrange(1000) for _ in range(100)] for d in data: lst.append(d) tc.assertEqual(100, len(lst)) tc.assertEqual(min(data), lst.min()) tc.assertEqual(max(data), lst.max()) for x in data: tc.assertEqual(data.index(x), lst.index(x)) tc.assertEqual(data.count(x), lst.count(x)) with tc.assertRaises(ValueError): lst.index(1000) lst = LinkedList() for d in (1, 2, 1, 2, 1, 1, 1, 2, 1): lst.append(d) tc.assertEqual(1, lst.index(2)) tc.assertEqual(1, lst.index(2, 1)) tc.assertEqual(3, lst.index(2, 2)) tc.assertEqual(7, lst.index(2, 4)) tc.assertEqual(7, lst.index(2, 4, -1)) with tc.assertRaises(ValueError): lst.index(2, 4, -2)
1 3 (4) 5 7 op = 1 + 3 n = 5, median = n 1 3 (5) 7 9 op = 2 + 4 n = 6, median = n 1 3 5 (6) 7 9 11 op = 1 + 3 + 5 n = 7, median = n 1 3 5 (7) 9 11 13 op = 2 + 4 + 6 ''' def minOperations(self, n: int) -> int: a1 = 1 + n % 2 i = n // 2 ai = a1 + (i - 1) * 2 return ((a1 + ai) * i) // 2 if __name__ == '__main__': t = TestCase() s = Solution() t.assertEqual(2, s.minOperations(3)) t.assertEqual(4, s.minOperations(4)) print('OK!')
return repr(self.data) # In[38]: from unittest import TestCase import random tc = TestCase() h = Heap() random.seed(0) for _ in range(10): h.add(random.randrange(100)) tc.assertEqual(h.data, [97, 61, 65, 49, 51, 53, 62, 5, 38, 33]) # In[39]: from unittest import TestCase import random tc = TestCase() h = Heap(lambda x: -x) random.seed(0) for _ in range(10): h.add(random.randrange(100)) tc.assertEqual(h.data, [5, 33, 53, 38, 49, 65, 62, 97, 51, 61])
# https://www.codewars.com/kata/find-the-unique-number-1/train/python from unittest import TestCase def find_uniq(arr): return list(filter(lambda x: arr.count(x) == 1, set(arr)))[0] or 0 test = TestCase() test.assertEqual(find_uniq([ 1, 1, 1, 2, 1, 1 ]), 2) test.assertEqual(find_uniq([ 0, 0, 0.55, 0, 0 ]), 0.55) test.assertEqual(find_uniq([ 3, 10, 3, 3, 3 ]), 10)
def test_case_6(): test_log("testing bulk operations") tc = TestCase() lst = ArrayList() lst2 = ArrayList() lst3 = lst + lst2 tc.assertIsInstance(lst3, ArrayList) tc.assertEqual([], arrayListToList(lst3)) data = [random.randrange(1000) for _ in range(50)] data2 = [random.randrange(1000) for _ in range(50)] lst.data = ConstrainedList.create(data) lst.len = len(lst.data) lst2.data = ConstrainedList.create(data2) lst2.len = len(lst.data) lst3 = lst + lst2 tc.assertEqual(100, len(lst3)) tc.assertEqual(data + data2, arrayListToList(lst3)) lst.clear() tc.assertEqual([], arrayListToList(lst)) lst.data = ConstrainedList.create( [random.randrange(1000) for _ in range(50)]) lst2 = lst.copy() tc.assertIsNot(lst, lst2) tc.assertIsNot(lst.data, lst2.data) tc.assertEqual(arrayListToList(lst), arrayListToList(lst2)) lst.clear() lst.extend(range(10)) lst.extend(range(10, 0, -1)) lst.extend(data.copy()) tc.assertEqual(70, len(lst)) tc.assertEqual( list(range(10)) + list(range(10, 0, -1)) + data, arrayListToList(lst)) suc()
def left(s): return s[:len(s) // 2] def right(s): l = len(s) return s[(l // 2) + (l % 2):] def luck_check(string): return sum_of_digits(left(string)) == sum_of_digits(right(string)) test = TestCase() test.assertEqual(left("003111"), "003") test.assertEqual(right("003111"), "111") test.assertEqual(luck_check("003111"), True) test.assertEqual(left("813372"), "813") test.assertEqual(right("813372"), "372") test.assertEqual(luck_check("813372"), True) test.assertEqual(left("17935"), "17") test.assertEqual(right("17935"), "35") test.assertEqual(luck_check("17935"), True) test.assertEqual(left("56328116"), "5632") test.assertEqual(right("56328116"), "8116") test.assertEqual(luck_check("56328116"), True)
def test_infix_to_postfix_2(): tc = TestCase() tc.assertEqual(infix_to_postfix('1 + 2 * 3'), '1 2 3 * +') tc.assertEqual(infix_to_postfix('1 / 2 + 3 * 4'), '1 2 / 3 4 * +') tc.assertEqual(infix_to_postfix('1 * 2 * 3 + 4'), '1 2 * 3 * 4 +') tc.assertEqual(infix_to_postfix('1 + 2 * 3 * 4'), '1 2 3 * 4 * +')
def test_median_1(): tc = TestCase() tc.assertEqual([3, 2.0, 3, 6.0, 9], running_medians([3, 1, 9, 25, 12]))
@author: ody ''' from unittest import TestCase from typing import List class Solution: ''' Tip: Solve q508 before try this 5.64% (another top submission result in 5.87%) ''' def maxProfit(self, prices: List[int]) -> int: if len(prices) == 0: return 0 dpsum = 0 maxsum = 0 for x in range(1, len(prices)): prof = prices[x] - prices[x - 1] dpsum = max(dpsum + prof, prof) # Kadane's maxsum = max(dpsum, maxsum) return maxsum if maxsum > 0 else 0 if __name__ == '__main__': t = TestCase() s = Solution() t.assertEqual(5, s.maxProfit([7, 1, 5, 3, 6, 4])) t.assertEqual(0, s.maxProfit([7, 6, 4, 3, 1])) print('OK!')
def test_median_2(): tc = TestCase() vals = [random.randrange(10000) for _ in range(1000)] tc.assertEqual(running_medians_naive(vals), running_medians(vals))
def test_case_2(): # (4 points) test stringification test_log("test stringification ") tc = TestCase() lst = ArrayList() tc.assertIsInstance(lst.data, ConstrainedList) tc.assertEqual('[]', str(lst)) tc.assertEqual('[]', repr(lst)) lst.data = ConstrainedList.create([1]) lst.len = len(lst.data) tc.assertEqual('[1]', str(lst)) tc.assertEqual('[1]', repr(lst)) lst.data = ConstrainedList.create([10, 20, 30, 40, 50]) lst.len = len(lst.data) tc.assertEqual('[10, 20, 30, 40, 50]', str(lst)) tc.assertEqual('[10, 20, 30, 40, 50]', repr(lst)) suc()
count1 -= matrix[y][c] if count1 == side * side: sqr += 1 return sqr class Solution: ''' 95.88% ''' def countSquares(self, matrix: List[List[int]]) -> int: res = sum(matrix[0]) for y in range(1, len(matrix)): res += matrix[y][0] for x in range(1, len(matrix[y])): if matrix[y][x] == 1: matrix[y][x] = min(matrix[y - 1][x - 1], matrix[y][x - 1], matrix[y - 1][x]) + 1 res += matrix[y][x] return res if __name__ == '__main__': t = TestCase() s = Solution() t.assertEqual(15, s.countSquares([[0, 1, 1, 1], [1, 1, 1, 1], [0, 1, 1, 1]])) t.assertEqual(7, s.countSquares([[1, 0, 1], [1, 1, 0], [1, 1, 0]])) print('OK!')
def inter(s, d, r): s = int(s, 8) d = int(d, 8) r = int(r) ''' 0 s s + 0 (r = 1) 1 s + d, s + 2d s + d + 1 (r = 2) 2 s + 3d, s + 4d, s + 5d s + 3d + 2 (r = 3) 3 s + 6d, s + 7d, s + 8d, s + 9d s + 6d + 3 (r = 4) r s0, s0 + d, s0 + 2d, ... s + (r(r-1)/2) d ''' sr0 = s + r * (r - 1) // 2 * d n = 0 for i in range(r): n += sum8(sr0 + i * d) # print('{:o}'.format(sr0 + i * d)) return n if __name__ == '__main__': t = TestCase() t.assertEqual(36, inter('2', '3', '5')) t.assertEqual(38, inter('221', '2', '4')) t.assertEqual(230, inter('1', '4', '20')) t.assertEqual(99, inter('10', '10', '10')) t.assertEqual(178, inter('3245', '5', '11')) print('OK!')
def should_equal(test: unittest.TestCase, except_value, real_value): return test.assertEqual(except_value, real_value)