Advertisement
Guest User

Untitled

a guest
Oct 20th, 2019
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.88 KB | None | 0 0
  1. from utils import readcsv, writecsv
  2. from collections import defaultdict, deque
  3.  
  4. PRIORITY = ['credit_card', 'bank_account', 'device']
  5. pre = '.'
  6.  
  7.  
  8. class Klass:
  9.     def __init__(self, name, val):
  10.         self.name = name
  11.         self.val = val
  12.  
  13.     @property
  14.     def priority(self):
  15.         return PRIORITY.index(self.name)
  16.  
  17.     def __repr__(self):
  18.         return f'{self.name}:{self.val}'
  19.  
  20.  
  21. def bfs(graph, start, end):
  22.     q = deque()
  23.     q.append((start, [], 0))
  24.     vis = set()
  25.     vis.add(start)
  26.  
  27.     ans = []
  28.     min_dis = float('inf')
  29.     while q:
  30.         cur, path, dis = q.popleft()
  31.  
  32.         if dis > min_dis:
  33.             continue
  34.  
  35.         if cur == end:
  36.             min_dis = min(min_dis, dis)
  37.             ans.append(path)
  38.  
  39.         for node, val in graph[cur]:
  40.             if node not in vis:
  41.                 q.append((node, path + [(val.priority, val.val, val, node)], dis + 1))
  42.                 vis.add(node)
  43.  
  44.     if ans:
  45.         ans.sort()
  46.         ans = ans[0]
  47.         return '-'.join([f'"{val}"->{node}' for _, _, val, node in ans])
  48.  
  49.  
  50. def make_graph(graph, f, name):
  51.     data = readcsv(f)
  52.     maps = defaultdict(list)
  53.  
  54.     for id, val in data:
  55.         maps[val].append(id)
  56.  
  57.     for id, val in data:
  58.         neighbors = maps[val]
  59.         for neighbor in neighbors:
  60.             if neighbor != id:
  61.                 graph[id].append((neighbor, Klass(name, val)))
  62.  
  63. graph = defaultdict(list)
  64. make_graph(graph, f'data/{pre}/bank_accounts.csv', 'bank_account')
  65. make_graph(graph, f'data/{pre}/credit_cards.csv', 'credit_card')
  66. make_graph(graph, f'data/{pre}/devices.csv', 'device')
  67. orders = readcsv(f'data/{pre}/orders.csv')
  68.  
  69. ans = [['orderid', 'is_fraud']]
  70. for oid, bid, sid in orders:
  71.     path = bfs(graph, bid, sid)
  72.     if path:
  73.         ans.append([oid, f'{bid}-{path}'])
  74.     else:
  75.         ans.append([oid, 'not fraud'])
  76.  
  77. writecsv('ans.csv', ans)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement