Move History

Fork Selected
  • Mathematics
    Algorithms
    Logic
    Numbers
    Data Types
    Code
    def is_happy(x, *, _trie=[False,10*[False]+[[True]]]+8*[False]+[[False]]):
        a = [False]
        while True:
            z = 0 # wasting some operations when x is in _trie. nobody cares though.
            t = _trie
            while x:
                r = x%10
                x //= 10
                z += r*r
                if t[r]:
                    t = t[r]
                else:
                    t[r] = (11-(not r))*[False]
                    t = t[r]
                    while x:
                        r = x%10
                        x //= 10
                        z += r*r
                        t[r] = (11-(not r))*[False]
                        t = t[r]
                    break
            else:
                if t[10]:
                    a[0] = t[10][0]
                    return a[0]
            t[10] = a
            x = z
    
    Preloaded Code
    #hi
    Test Cases
    import codewars_test as test
    from solution import is_happy
    
    # test.assert_equals(actual, expected, [optional] message)
    @test.describe("Example")
    def test_group():
        @test.it("test case")
        def test_case():
            test.assert_equals(is_happy(3), False)
            test.assert_equals(is_happy(4), False)
            test.assert_equals(is_happy(7), True)
            test.assert_equals(is_happy(19), True)
            test.assert_equals(is_happy(103), True)
            test.assert_equals(is_happy(487), True)
            test.assert_equals(is_happy(1663), True)
            test.assert_equals(is_happy(1665), False)
            test.assert_equals(is_happy(1000000000), True)
            test.assert_equals(is_happy(10000000001), False)
    #         test.assert_equals(is_happy(), True)
    
  • Code
    • class ref:
    • def __init__(self, data):
    • self.data = data
    • def is_happy(x, *, _trie=[False,10*[False]+[ref(True)]]+8*[False]+[ref(False)]):
    • a = ref(False)
    • def is_happy(x, *, _trie=[False,10*[False]+[[True]]]+8*[False]+[[False]]):
    • a = [False]
    • while True:
    • z = 0 # wasting some operations when x is in _trie. nobody cares though.
    • t = _trie
    • while x:
    • r = x%10
    • if not t[r]:
    • t[r] = (11-(not r))*[False]
    • t = t[r]
    • x //= 10
    • z += r**2
    • if t[-1]:
    • a.data = t[-1].data
    • return a.data
    • t[-1] = a
    • z += r*r
    • if t[r]:
    • t = t[r]
    • else:
    • t[r] = (11-(not r))*[False]
    • t = t[r]
    • while x:
    • r = x%10
    • x //= 10
    • z += r*r
    • t[r] = (11-(not r))*[False]
    • t = t[r]
    • break
    • else:
    • if t[10]:
    • a[0] = t[10][0]
    • return a[0]
    • t[10] = a
    • x = z