我正试图解决以下问题:
编写一个函数解(L),它接受一个正整数列表l,并计算(li,lj,lk)的“幸运三倍”数,其中列表索引满足i
例如,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
发布于 2022-06-03 09:30:22
如果对完整列表和剩余列表进行嵌套迭代,那么比较这两个项以检查它们是否为除数。结果算作“三重”的起始数和中间数,
然后在第二轮,它会计算出第三轮。您所需要做的就是跟踪哪些通过了除数测试。
例如
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
https://stackoverflow.com/questions/72483617
复制相似问题