Created
March 31, 2019 19:47
-
-
Save timbledum/81b9290682d048d73fc2487b0c7539c2 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import csv | |
from itertools import groupby | |
# Constants | |
TRANSACTIONS_FILE = "transactions.csv" | |
PRODUCTS_FILE = "products.csv" | |
def get_city_mapping(): | |
with open(PRODUCTS_FILE) as file: | |
reader = csv.DictReader(file) | |
mapping = {} | |
for row in reader: | |
mapping[row["prod_id"]] = row["city"] | |
return mapping | |
def get_visited_transactions(city_mapping): | |
with open(TRANSACTIONS_FILE) as file: | |
reader = csv.DictReader(file) | |
data = [] | |
for row in reader: | |
product = row["prod_id"] | |
city = city_mapping[product] | |
visited = int(row["visited"]) | |
data.append((city, visited)) | |
return data | |
def main(): | |
city_mapping = get_city_mapping() | |
data = get_visited_transactions(city_mapping) | |
data.sort() | |
for city, group in groupby(data, key=lambda row: row[0]): | |
visited_data = [row[1] for row in group] | |
orders = len(visited_data) | |
visited = sum(visited_data) | |
percentage = visited / orders * 100 | |
print( | |
f"City {city} had {orders:3d} orders, {visited:3d} visits," | |
f" and a percentage visited of {percentage:5.1f}%" | |
) | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment