入坑codewars第21天-Numbers that are a power of their sum of digits

新年第一道题,已经几个月没写了,哎,毕业设计整不出

The number 81 has a special property, a certain power of the sum of its digits is equal to 81 (nine squared). Eighty one (81), is the first number in having this property (not considering numbers of one digit). The next one, is 512. Let's see both cases with the details

8 + 1 = 9 and 92 = 81

512 = 5 + 1 + 2 = 8 and 83 = 512

We need to make a function, power_sumDigTerm(), that receives a number n and may output the n-th term of this sequence of numbers. The cases we presented above means that

power_sumDigTerm(1) == 81

power_sumDigTerm(2) == 512

Happy coding!

题意:

数字81有一个特殊的性质,它的数字之和的某次方等于81(9的平方)81(81)是具有此属性的第一个数字(不考虑一位数的数字)。下一个是512。让我们看看这两种情况的细节

思路:

这道题目的主要思路是创建一个新的数组,将所有可能的数字加入到数组中。 
我们的首要目标就是要找出这些数字。这里需要巧妙的使用map() 函数

首先将输入的数字转换成字符串,对字符串中的每一个字符,也就是每一位数字用map映射为int格式,然后对他们求和。 
通过这个map 映射判断,就可以找出所有符合条件的数字了。

这一点优化很节约时间!!!

代码如下:

def power_sumDigTerm(n):
    #your code here
    power_sum = []
    for i in range(2, 100):
        for j in range(2, 50):
            pow_i = i ** j
            if sum(map(int, str(pow_i))) == i: #计算每一位数字之和:如81:8+1=>9*9=81
                power_sum.append(pow_i)
    power_sum.sort()
    return power_sum[n-1]

感谢https://blog.csdn.net/u011562123/article/details/82316333 提供思路。让我学会map函数

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值