Codewars算法題(8)

第26題:

問題:


問題描述:

給定一個列表,和一個整數s,找出列表中兩數之和爲s,的兩個數,並返回,若有若干對這樣的數,那麼選擇相距較短的,在相距較短的中再找出index小的。

評分較高答案:

def sum_pairs(lst, s):
    cache = set()
    for i in lst:
        if s - i in cache:
            return [s - i, i]
        cache.add(i)
該方法用減法推倒~~~~,大神就是大神啊

第27題:

問題:

Divisors of 42 are : 1, 2, 3, 6, 7, 14, 21, 42. These divisors squared are: 1, 4, 9, 36, 49, 196, 441, 1764. The sum of the squared divisors is 2500 which is 50 * 50, a square!

Given two integers m, n (1 <= m <= n) we want to find all integers between m and n whose sum of squared divisors is itself a square. 42 is such a number.

The result will be an array of arrays(in C an array of Pair), each subarray having two elements, first the number whose squared divisors is a square and then the sum of the squared divisors.

#Examples:

list_squared(1, 250) --> [[1, 1], [42, 2500], [246, 84100]]
list_squared(42, 250) --> [[42, 2500], [246, 84100]]
問題描述:

 給定一個區間[m, n] 求這個區間內符合條件的 數對, [i, f[i]] 即 f[i] 爲 i的所有因子的平方和且f[i]爲平方數

評分較高代碼:

CACHE={}
def squared_cache(number):
    if number not in CACHE:
        divisors = [x for x in range(1, number + 1) if number % x == 0]
        CACHE[number] = sum([x * x for x in divisors])
    return CACHE[number]

def list_squared(m, n):
    ret = []
    for number in range(m, n + 1):
        divisors_sum = squared_cache(number)
        if (divisors_sum ** 0.5).is_integer():
            ret.append([number, divisors_sum])
    return ret
其中:squared_cache函數是求整數的因子的平方和

自己代碼:(有誤)

def factors(p):
    divisors = []
    for k in range(1, p + 1):
        if p % k == 0:
            divisors.append(k)
    return divisors
def list_squared(m, n+1):
    output = []
    sum = 0
    for num in (m, n):
        for i in factors(num):
            sum += i*i
            if (sum ** 0.5).is_integer()
                return output.append([num, sum])
現在我的代碼是錯誤的,但是我仍找不出原因。函數factors()是求一個數的所有因子,並以列表形式返回。希望看到帖子的大神幫幫忙~~~,菜鳥兒在此感謝了!



201707281111持續更新~~~~

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