-
MathematicsAlgorithmsLogicNumbersData 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) .describe("Example") def test_group(): .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)
Output:
-
Code class ref:def __init__(self, data):self.data = datadef 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**2if t[-1]:a.data = t[-1].datareturn a.datat[-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
- All
- {{group.name}} ({{group.count}})
This comment has been reported as {{ abuseKindText }}.
Show
This comment has been hidden. You can view it now .
This comment can not be viewed.
- |
- Reply
- Edit
- View Solution
- Expand 1 Reply Expand {{ comments?.length }} replies
- Collapse
- Remove
- Remove comment & replies
- Report
{{ fetchSolutionsError }}