您的位置:首页 > 编程语言 > Python开发

codewars习题(1),python3,playing with digits,6级,算法

2018-01-20 13:22 435 查看
描述:

Some numbers have funny properties. For example:

89 --> 8¹ + 9² = 89 * 1

695 --> 6² + 9³ + 5⁴= 1390 = 695 * 2
46288 --> 4³ + 6⁴+ 2⁵ + 8⁶ + 8⁷ = 2360688 = 46288 * 51

Given a positive integer n written as abcd... (a, b, c, d... being digits) and a positive integer p we want to find a positive integer k, if it exists, such as the sum of the digits of n taken to the successive powers of p is equal
to k * n. In other words:

Is there an integer k such as : (a ^ p + b ^ (p+1) + c ^(p+2) + d ^ (p+3) + ...) = n * k

If it is the case we will return k, if not return -1.

Note: n, p will always be given as strictly positive integers.

算法思想:给定两个参数,n,p,将n中每一个数字提取出来,并加入一个列表里面,再求出总和计算k值

但最终k值会是浮点数,于是加一个限定,不是整数则返回-1,是整数则返回k值

函数代码;def dig_pow(n, p):

    a = []

    b = n

    c = p

    s = 0

    d = 1

    while d > 0:#d判断执行次数

        d = b // 10

        b = b % 10

        a.append(b)

        b = d

    i = -1

    q = len(a)

    while q > 0:

        h = a [q - 1]

        s = s + (h ** c)

        c +=1

        q -=1

    l = s / n

    v = l - int(l)#v判断浮点数值是不是整数

    if s < n or v > 0:

        return -1

    else:

        return l 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐