Why doesn't this code work (Leetcode in Python)? -
class solution: def ishappy(self, n): list_n, l, ls, num = [n,], 0, 0, 0 while num != 1: if l != ls: return false num = sum([int(i)**2 in list(str(n))]) list_n.append(num) l, ls = len(list_n), len(set(list_n)) return true
input: 7
output: false
expected: true
it's happy number | leetcode oj
write algorithm determine if number "happy".
a happy number number defined following process: starting positive integer, replace number sum of squares of digits, , repeat process until number equals 1 (where stay), or loops endlessly in cycle not include 1. numbers process ends in 1 happy numbers.
to answer question: code fails because you're confusing num
, n
. in particular, compute num
n
, , neither ever changes. rid of 1 of them, less confusing. should learn debug, btw... printing num
or n
inside loop have made clear what's happening.
using set btw easier , faster, try well. here's 1 way:
def ishappy(n): stop = {1} while n not in stop: stop.add(n) n = sum(int(d)**2 d in str(n)) return n == 1
and here's 1 uses 2 single ints. can see how works?
def ishappy(n): s = lambda n: sum(int(d)**2 d in str(n)) m = s(n) while m != n: n, m = s(n), s(s(m)) return n == 1
Comments
Post a Comment