Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Optimized solution for REp007 Challenge: Cheapest Cit #74

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions submissions/REp007/main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import pandas as pd
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is this an external library ? Unfortunately only standard python library can be used


def remove_duplicates(file_name):
input_data = pd.read_csv(file_name, header=None, names=["City", "Product", "Price"])
cleaned_data = []

for city in input_data["City"].unique():
products = input_data[input_data["City"] == city]["Product"].unique()
for product in products:
df_filtered = input_data[(input_data["City"] == city) & (input_data["Product"] == product)]
min_price_row = df_filtered.loc[df_filtered["Price"].idxmin()]
cleaned_data.append(min_price_row.to_dict())

cleaned_data = pd.DataFrame(cleaned_data)
return cleaned_data

def get_cheapest_city(data):
city_totals = data.groupby('City')['Price'].sum()
return city_totals.idxmin(), city_totals.loc[city_totals.idxmin()]

def get_top_5_cheapest_products(data, cheapest_city):
cheapest_city_data = data[data["City"] == cheapest_city]
top_5_cheapest_products = cheapest_city_data.sort_values(by=['Price', 'Product']).head(5)
return top_5_cheapest_products

if __name__ == '__main__':
file_name = "input.txt"
input_data = remove_duplicates(file_name)
cheapest_city, cheapest_city_sum_product = get_cheapest_city(input_data)
top_5_cheapest_products = get_top_5_cheapest_products(input_data, cheapest_city)

# Write the results to the output file
with open("output.txt", "w") as f:
f.write(f"{cheapest_city} {cheapest_city_sum_product:.2f}\n")
for index, row in top_5_cheapest_products.iterrows():
f.write(f"{row['Product']} {row['Price']:.2f}\n")