zoukankan      html  css  js  c++  java
  • 4.黑洞数

    一般方法:

    #!/usr/bin/env python
    # encoding: utf-8
    """
    @author: 侠之大者kamil
    @file: 4.黑洞数.py
    @time: 2016/3/21 18:16
    """
    # a = [4,6,2,4,5]
    # a.sort()
    # print(a)
    # print(a[::-1])
    # def func():
    #     pass
    # b = 254
    # list_b = []
    # while b >0:
    #     list_b.append(b % 10)
    #     b  //= 10
    # print(list_b)
    # list_b = list_b[::-1]
    # s = 0
    # for x in list_b:
    #     s = s *10 +x
    # print(s)
    def fun(n):
        print(n)
        a =[]
        k = n
        while k >0:
            a.append(k % 10)
            k //=10
        a.sort()# 小到大排序  [2, 3, 5, 8]
        #print(a)
        s1 = 0
        for x in a[::-1]:#反转
            s1  = s1 *10 +x  # 8532
        s2 = 0
        for x in a:
            s2 = s2 *10 + x # 2358
        if s1 -s2 ==n:
            return n
        else:
            return fun(s1 - s2)
    res = fun(1234)
    print("rea:",res)

    优化后

    from functools import reduce
    def fun(n):
        print(n)
        a = [int(c) for c in str(n)]
        a.sort()
        s1  = reduce(lambda x,y: 10*x + y ,a[::-1])
        s2  = reduce(lambda x,y: 10*x + y,a)
        return n if s1 -s2 == n else fun(s1 - s2)
    res = fun(1234)
    print("res:",res)
    公众号请关注:侠之大者
  • 相关阅读:
    AnyVal与AnyRef
    安装Zookeeper
    Kafka
    ZooKeeper总结
    Idea中JDK为1.8,还提示Diamond types are not supported at this language level
    Hive 和 Mysql
    Spark练习代码
    响应状态码
    http简介
    csrf
  • 原文地址:https://www.cnblogs.com/kamil/p/5307364.html
Copyright © 2011-2022 走看看