Advertisement
Guest User

Untitled

a guest
Oct 23rd, 2018
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.90 KB | None | 0 0
  1. import csv
  2. import re
  3. import sys
  4.  
  5. from collections import (
  6.     Counter,
  7.     defaultdict,
  8. )
  9.  
  10.  
  11. LANGUAGE_REGEXP = re.compile(r'\((.+)\)')
  12. COUNTRY_REGEXP = re.compile(r'(\w{2,})/')
  13.  
  14.  
  15. def get_country(text):
  16.     found = COUNTRY_REGEXP.search(text)
  17.     return found.group(1) if found else found
  18.  
  19.  
  20. def get_email(text):
  21.     return text.rsplit('/', 1)[0]
  22.  
  23.  
  24. def get_income(text):
  25.     if text:
  26.         return float(text.rsplit('/', 1)[-1])
  27.     return 0
  28.  
  29.  
  30. def get_language(text):
  31.     found = LANGUAGE_REGEXP.search(text)
  32.     return found.group(1) if found else found
  33.  
  34.  
  35. def question_1(rows):
  36.     return Counter(map(get_language, rows[0].keys())).most_common(1)
  37.  
  38.  
  39. def question_2(rows):
  40.     persons = set()
  41.     for row in rows:
  42.         persons.update(
  43.             {
  44.                 get_email(person) for key, person in row.items()
  45.                 if person and get_language(key).lower() == 'python'
  46.             }
  47.         )
  48.     return len(persons)
  49.  
  50.  
  51. def question_3(rows):
  52.     income_per_language = defaultdict(int)
  53.     for row in rows:
  54.         for key, data in row.items():
  55.             if data:
  56.                 income_per_language[get_language(key)] += get_income(data)
  57.     return max(
  58.         (income, language) for language, income in income_per_language.items()
  59.     )[-1]
  60.  
  61.  
  62. def question_4(rows):
  63.     cost_per_country = defaultdict(int)
  64.     for row in rows:
  65.         for key, data in row.items():
  66.             if data:
  67.                 cost_per_country[get_country(data)] += get_income(data)
  68.     return max(
  69.         (cost, country) for country, cost in cost_per_country.items()
  70.     )[-1]
  71.  
  72.  
  73. if __name__ == '__main__':
  74.     with open(sys.argv[1], 'r') as f:
  75.         csv_dict = csv.DictReader(f, delimiter=';')
  76.         rows = list(csv_dict)
  77.     print(f'1) {question_1(rows)}')
  78.     print(f'2) {question_2(rows)}')
  79.     print(f'3) {question_3(rows)}')
  80.     print(f'4) {question_4(rows)}')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement