[Microsoft面经】Number of fractions that sum up to 1 Microsoft OA 数据岗

胖蛋 2020-6-30 1874


最新回复 (1)
  • Crusader 2021-3-5
    0 引用 2
    
    from collections import defaultdict
    
    def gcd(a, b):
       if a == 0:
           return b
       return gcd(b % a, a)
    
    def number_of_ways(numerators, denominators):
       if len(numerators) != len(denominators):
           # return 0 for uneven/invalid pairs of numerators and denominators
           return 0
    
       m = defaultdict(set)
    
       for i in xrange(0, len(numerators)):
           new_n = numerators[i]
           new_d = denominators[i]
           if denominators[i] >= numerators[i]:
               common = gcd(numerators[i], denominators[i])
               new_n = numerators[i] / common
               new_d = denominators[i] / common
           m[(new_n, new_d)].add(i)
    
       t = 0
       s = 0
       for (n, d) in m.keys():
           if n == d - n:
               t += len(m[n, d])*(len(m[n, d])-1) / 2
           elif (d-n, d) in m:
               s += len(m[n, d]) * len(m[d - n, d])
    
       return t + s / 2
    
    if __name__ == "__main__":
       X = [1, 1, 2]
       Y = [3, 2, 3]
       print number_of_ways(X, Y) == 1
    
       X = [1, 1, 1]
       Y = [2, 2, 2]
       print number_of_ways(X, Y) == 3
    
       X = [1, 2, 3, 1, 2, 12, 8, 4]
       Y = [5, 10, 15, 2, 4, 15, 10, 5]
       print number_of_ways(X, Y) == 10
    
返回