简体   繁体   English

脚本的效率(找到一对具有相同余数的整数)

[英]Efficiency of the script (finding a pair of integers which have the same remainder)

I am trying to find a pair (x,y) in A such that xy = 0 (mod n) where inputs are a positive integer n, a set A of m nonnegative integers and m > n.我试图在 A 中找到一对 (x,y),使得 xy = 0 (mod n),其中输入为正 integer n,一组由 m 个非负整数和 m > n 组成的 A。 To run the code below I took an m and n just for the sake of running an example.为了运行下面的代码,我拿了一个 m 和 n 只是为了运行一个例子。

Below is the script I have written.下面是我写的脚本。

I wonder if there is a more efficient way to write the script我想知道是否有更有效的方法来编写脚本

import numpy as np import sys

n = 10 
m = 12

def functi(n, m):

  A = [0] * m

  for i in range(m):

    A[i] = np.random.randint(0,34)
   

  X = [-1] * n


  for i in range(len(A)-1,-1,-1) :  #loop backwards
    a = A[i]
    A.pop(i)
    r = a % n

    if X[r] == -1:
      X[r] = a
    else:
     return(X[r], a)
  

pair = functi(n, m) 
print(pair)

Note that your function doesn't have the parameters described by the problem -- it should take n and A as parameters, not take an m and generate its own A .请注意,您的 function 没有问题描述的参数 - 它应该将nA作为参数,而不是采用m并生成自己的A

The problem is much easier if you look at it as simply "find a pair of numbers with the same value mod n".如果您将其简单地视为“找到一对具有相同值 mod n 的数字”,则问题会容易得多。 An simple approach to this is to bucket all of the numbers according to their value % n , and return a bucket once it has two numbers in it.一个简单的方法是根据它们的值% n对所有数字进行存储,并在其中包含两个数字时返回一个存储桶。 That way you don't need to compare each pair of values individually to see if they match.这样您就不需要单独比较每对值来查看它们是否匹配。

>>> import random
>>> def find_equal_pair_mod_n(n, A):
...     assert len(A) > n
...     mods = {}
...     for i in A:
...         xy = mods.setdefault(i % n, [])
...         xy.append(i)
...         if len(xy) > 1:
...             return tuple(xy)
...
>>> find_equal_pair_mod_n(10, [random.randint(0, 34) for _ in range(12)])
(26, 6)
>>> find_equal_pair_mod_n(10, [random.randint(0, 34) for _ in range(12)])
(30, 10)
>>> find_equal_pair_mod_n(10, [random.randint(0, 34) for _ in range(12)])
(32, 32)
>>> find_equal_pair_mod_n(10, [random.randint(0, 34) for _ in range(12)])
(1, 1)
>>> find_equal_pair_mod_n(10, [random.randint(0, 34) for _ in range(12)])
(28, 8)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM