Feb-17-2019, 11:22 AM
That was an unforgivable error... This is where writing some tests are highly desirable.
I have rewritten my code, added some tests, and now it seems work fine.
I have rewritten my code, added some tests, and now it seems work fine.
decompose = lambda x: list(map(int, str(x))) # x assumed to be a positive integer compose = lambda x: int(''.join(map(str, x))) # x assumed to be a list of digits (each digit is int) is_asc = lambda x: compose(sorted(decompose(x))) == x # check if x is alredy "good" number is_dsc = lambda x: compose(sorted(decompose(x)[::-1])[::-1]) == x def min_asc(x): def _make_preorder(x): d = decompose(x) res = d[:] m = None for j in range(len(d) - 1): if d[j] > d[j + 1] and not m: m = d[j] res[j + 1] = m or d[j + 1] return compose(res) return _make_preorder(x + 1) if is_asc(x) else _make_preorder(x) def min_dsc(x): def _make_preorder(x): d = decompose(x) res = d[:] for j in range(len(d) - 1, 0, -1): if res[j] > res[j - 1]: res[j - 1] += 1 res[j:] = [0] * (len(d) - j) return compose(res) return _make_preorder(x + 1) if is_dsc(x) else _make_preorder(x) asc_autotest_data = ((3124123, 3333333), (1, 2), (10, 11), (99, 111), (154, 155), (277, 278), (0, 1), (9, 11), (47893, 47899), (int('1' * 39 + '0' * 90 + '7' * 100), int('1' * (39 + 90 + 100))), # a very big num (99999, 111111), (123614270121, 123666666666) ) dsc_autotest_data = ((1, 2), (9, 10), (543105, 543110), (299, 300), (109012, 110000), (0, 1), (999889, 999900), (101, 110), (99999, 100000), (1009, 1100), (0, 1), (int('1' * 100 +'0'*100 + '9'*100), int('1'*101 + '0' * 199)) # a very big num ) def test_functions(data, f): print("Testing {}....".format(f.__name__)) for a, b in data: if f(a) != b: print("Failed test: {} != {}".format(f(a), b)) break else: print("All tests were passed.") return print("Some tests were failed.") if __name__ == '__main__': test_functions(asc_autotest_data, min_asc) test_functions(dsc_autotest_data, min_dsc)