对数量 [英] Number of pairs

查看:113
本文介绍了对数量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图写一个code,它采用

  • 微米。的的,整数列表

  • ñ。 B 的,整 并返回对(M,N)用米的数量,n个的的使得| MN |&其中; = B。

到目前为止,我有这个

 高清nearest_pairs(A,B):
    米= []
    N = INT
    num_pairs = 0
    返回num_pairs

高清的main():
    #最近的对是(1,2),(2,1),(2,5)和(5,2)

    X = nearest_pairs([1,2,5],3)
    打印(nearest_pairs([1,2,5〕,3)=,nearest_pairs([1,2,5〕,3))

    #最近的对是(1,2)和(2,1)
    Y = nearest_pairs([1,2,5],2)
    打印(nearest_pairs([1,2,5],2)=,nearest_pairs([1,2,5],2))

如果__name__ =='__main__':
    主要()
 

所需的输出应为

 >>> nearest_pairs([1,2,5],3)= 4
 

,其中图4是根据本限制接近对数。不过,我得到一个错误。任何人都可以使我朝着正确的方向?

解决方案

 从itertools进口排列
高清nearest_pairs(A,B):
    对于M,N的排列(一,二):
        如果ABS(M  -  N)其中; = B:
            收益率(M,N)
 

 >>>列表(nearest_pairs([1,2,5〕,3))
[(1,2),(2,1),(2,5),(5,2)]
>>>列表(nearest_pairs([1,2,5],2))
[(1,2),(2,1)]
 

如果你只是想计数:

 高清nearest_pairs_count(A,B):
    C,L = 0,LEN(一)
    对于i在范围(1):
        对于j的范围第(i + 1,1):
            如果ABS(A [1]  - 一个[j]的)其中; = b的:
                C + = 2
    回复C
 

I am trying to write a code that takes

  • m. a, a list of integers

  • n. b, an integer and returns the number of pairs (m,n) with m,n in a such that |m-n|<=b.

So far, I've got this

def nearest_pairs(a, b):
    m= []
    n= int
    num_pairs = 0
    return num_pairs

def main():
    # The nearest pairs are (1,2), (2,1), (2,5) and (5,2)

    x = nearest_pairs( [1,2,5] , 3 )
    print( "nearest_pairs([1, 2, 5], 3) = " , nearest_pairs([1, 2, 5], 3) )

    # The nearest pairs are (1,2) and (2,1)
    y = nearest_pairs( [1, 2, 5] , 2 )
    print( "nearest_pairs([1, 2, 5], 2) = " , nearest_pairs([1, 2, 5], 2) )

if __name__ == '__main__':
    main()

The desired output should look like

>>> nearest_pairs([1,2,5],3) = 4

where 4 is the number of close pairs according to the restrictions. However, I get an error. Could anyone lead me to the right direction?

解决方案

from itertools import permutations
def nearest_pairs(a, b):
    for m, n in permutations(a, 2):
        if abs(m - n) <= b:
            yield (m, n)

>>> list(nearest_pairs([1, 2, 5], 3))
[(1, 2), (2, 1), (2, 5), (5, 2)]
>>> list(nearest_pairs([1, 2, 5], 2))
[(1, 2), (2, 1)]

If you just want the count:

def nearest_pairs_count(a, b):
    c, l = 0, len(a)
    for i in range(l):
        for j in range(i + 1, l):
            if abs(a[i] - a[j]) <= b:
                c += 2
    return c

这篇关于对数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆