入坑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函數

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章