简体   繁体   中英

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. To run the code below I took an m and n just for the sake of running an example.

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 .

The problem is much easier if you look at it as simply "find a pair of numbers with the same value 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. 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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