我正在尝试编写一个带
的代码到目前为止,我已经有了这个
from itertools import permutations
def close_pairs(l, d):
for a,b in permutations(l, 2):
if (a - b) <= d and (b - a) <= d:
return len(a, b)
def main():
# The close pairs are (1,2), (2,1), (2,5) and (5,2)
# (1,5) and (5,1) don't count because their difference is 4 (which is >3)
x = close_pairs( [1,2,5] , 3 )
print( "close_pairs([1, 2, 5], 3) = " , close_pairs([1, 2, 5], 3) )
# The close pairs are (1,2) and (2,1)
y = close_pairs( [1, 2, 5] , 2 )
print( "close_pairs([1, 2, 5], 2) = " , close_pairs([1, 2, 5], 2) )
if __name__ == '__main__':
main()
所需的输出应该看起来像
>>> nearest_pairs([1,2,5],3) = 4,
其中4是根据限制的密切对的数量。但是,我没有这个。有人能引导我走向正确的方向吗?