Advertisement
rosien

Three rules

Sep 30th, 2020
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.71 KB | None | 0 0
  1. def freqQuery(queries):
  2.     result = []
  3.     d = {}
  4.     d_freq = {}
  5.     """
  6.    example - sample 2
  7.    d = number:frequency
  8.    {4: 2, 5: 2, 3: 0, 1:1}
  9.  
  10.    dict = frequency:numbers
  11.    {0: {3}, 2: {4, 5}, 1:{1}}
  12.    """
  13.     for q in queries:
  14.         if q[0] == 1:
  15.             # add 1 to d[q[1]]
  16.             d[q[1]] = d.get(q[1], 0) + 1
  17.  
  18.             # if d[q[1]] is not yet in d_freq then put an empty set as it's value
  19.             d_freq[d[q[1]]] = d_freq.get(d[q[1]], set([]))
  20.             # add frequency:number to dict d
  21.             d_freq[d[q[1]]].add(q[1])
  22.  
  23.             # if d[q[1]]-1 is not yet in d_freq then put an empty set as it's value
  24.             d_freq[d[q[1]] - 1] = d_freq.get(d[q[1]] - 1, set([]))
  25.             # discard the number at d[q[1]]-1
  26.             d_freq[d[q[1]] - 1].discard(q[1])
  27.  
  28.         elif q[0] == 2:
  29.             if d.get(q[1], 0):
  30.                 # if d[q[1]] is not yet in d_freq then put an empty set as it's value
  31.                 d_freq[d[q[1]]] = d_freq.get(d[q[1]], set([]))
  32.                 # discard the number at d[q[1]]
  33.                 d_freq[d[q[1]]].discard(q[1])
  34.  
  35.                 # if d[q[1]-1] is not yet in d_freq then put an empty set as it's value
  36.                 d_freq[d[q[1]] - 1] = d_freq.get(d[q[1]] - 1, set([]))
  37.                 # add the number at d[q[1]]-1
  38.                 d_freq[d[q[1]] - 1].add(q[1])
  39.  
  40.             # minus 1 to d[q[1]]
  41.             d[q[1]] = max(0, d.get(q[1], 0) - 1)
  42.  
  43.         else:
  44.             if d_freq.get(q[1], 0):
  45.                 result.append(1)
  46.             else:
  47.                 result.append(0)
  48.     return result
  49.  
  50.  
  51. q = [[1, 3], [2, 3], [3, 2], [1, 4], [1, 5], [1, 5], [1, 4], [3, 2], [2, 4], [3, 2]]
  52.  
  53.  
  54. print(freqQuery(q))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement