LeetCode 202 -- python 计算 happy number

第一篇贡献给python计算happy number~

 

def cal(n):
    s=str(n)
    sum=0
    for i in range(len(s)):
        sum+=int(s[i])**2
    return sum

a=77   # 13 139 ok; 4 5 6 not
# print (cal(a))
def itr(a):
    log_set=set([a])
    while a!=1:
        temp = cal(a)
        if temp in log_set:
            return False # False but not false
        else:
            log_set.add(temp)
            a=temp # lost as testing online
    return True

print ("itr(a): ",itr(a))

 

一个非常慢的方法

class Solution(object):
    def isHappy(self, n):
        """
        :type n: int
        :rtype: bool
        """
        def cal(n):
            s=str(n)
            sum=0
            for i in range(len(s)):
                sum+=int(s[i])**2
            return sum
        
        log_set=set([])
        while n!=1:
            temp = cal(n)
            if temp in log_set:
                return False
            else:
                log_set.add(temp)
                n=temp # lost as testing online
        return True

 

posted on 2019-05-27 23:45  Gilliana  阅读(248)  评论(0编辑  收藏  举报

导航