Simple Life

和这个世界交手这许多年   你是否光彩依旧,兴致盎然...

您现在的位置是:首页 爱折腾 爱折腾详情

找出happy number(python)

发布时间:2015-6-17 作者:Felix 浏览(1065)

        快乐数(happy number)有以下的特性:在给定的进位制下,该数字所有数位(digits)的平方和,得到的新数再次求所有数位的平方和,如此重复进行,最终结果必为1。

        Write an algorithm to determine if a number is “happy”.

        A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers.


Example: 19 is a happy number

  • 2 + 9 2 = 82

  • 2 + 2 2 = 68

  • 2 + 8 2 = 100

  • 2 + 0 2 + 0 2 = 1


python代码如下,找出100以内的:

def calculator(num):
    return sum(map(lambda x: int(x)**2, list(str(num))))
    
def func():
    happy = []
    for s in range(101):
        tmplist = []
        while 1:
            p = calculator(tmplist[-1]) if tmplist else calculator(s)
            if p == 1:
                happy.append(s)
                break
            if p in tmplist:
                break
            tmplist.append(p)
    return happy
    
if __name__ == '__main__':
    print func()


输出如下:

felix $  [1, 7, 10, 13, 19, 23, 28, 31, 32, 44, 49, 68, 70, 79, 82, 86, 91, 94, 97, 100]


上一篇: Django 数据库查询

下一篇: Redis 初探

基于 Django 搭建

服务器采用的 阿里云

域名来自 万网

苏ICP备16015443号

©2015-2016 felixglow.com.

GitHub

Design by Felix