Foobar幸运三重奏

Foobar Lucky Triple

我正在尝试解决以下问题:

编写一个函数 solution(l),它接受一个正整数列表 l 并计算 (li, lj, lk) 的“幸运三元组”的数量,其中列表索引满足 i < j < k 的要求。 l 的长度介于 2 和 2000 之间(包括端值)。 “幸运三元组”是一个元组 (x, y, z),其中 x 除以 y,y 除以 z,例如 (1, 2, 4)。 l 的元素介于 1 和 999999 之间(含)。该解决方案适合带符号的 32 位整数。有些列表是特意生成的,没有任何访问代码来甩掉间谍,所以如果没有找到三元组,return 0.

例如,[1, 2, 3, 4, 5, 6] 有三元组:[1, 2, 4], [1, 2, 6], [1, 3, 6],使得解决方案共 3 个。

我的解决方案只通过了前两个测试;我试图了解我的方法有什么问题,而不是实际的解决方案。以下是我的功能供参考:

def my_solution(l):
    from itertools import combinations
    if 2<len(l)<=2000:
        l = list(combinations(l, 3))
        l= [value for value in l if value[1]%value[0]==0 and value[2]%value[1]==0]
        #l= [value for value in l if (value[1]/value[0]).is_integer() and (value[2]/value[1]).is_integer()]
        
        if len(l)<0xffffffff:
            l= len(l)
            return l
        
    else:
        return 0

如果你对完整列表和剩余列表进行嵌套迭代,然后比较这两项以检查它们是否是除数...结果算作 'triple' 的开始和中间数字,

然后在第二轮计算第三轮...您需要做的就是一路追踪哪些通过了除数测试。

例如

def my_solution(l):
    row1, row2 = [[0] * len(l) for i in range(2)]  # Tracks which indices pass modulus
    for i1, first in enumerate(l):  
        for i2 in range(i1+1, len(l)):  # iterate the remaining portion of the list
            middle = l[i2]
            if not middle % first:  # check for matches
                row1[i2] += 1     # increment the index in the tracker lists..
                row2[i1] += 1     # for each matching pair
    result = sum([row1[i] * row2[i] for i in range(len(l))])  
    # the final answer will be the sum of the products for each pair of values.
    return result