新年第一道题,已经几个月没写了,哎,毕业设计整不出
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函数