Aug-21-2018, 04:55 PM
Disclaimer: all following can be considered as ranting
I found task description in github (Assessment file) to be very ambiguous. Every time I encounter such poorly defined tasks I become mean Monty. This made me provide some ideas below which are as bad (but should be working).
If .txt files in github are in correct format (no header rows, blank lines, empty spaces after commas etc) one could use csv.DictReader for files and do something along those lines:
To get name from ID:
I found task description in github (Assessment file) to be very ambiguous. Every time I encounter such poorly defined tasks I become mean Monty. This made me provide some ideas below which are as bad (but should be working).
If .txt files in github are in correct format (no header rows, blank lines, empty spaces after commas etc) one could use csv.DictReader for files and do something along those lines:
import csv with open('parts.txt', 'r') as f: fieldnames = ('PartID', 'Partname', 'PartCost') parts = list(csv.DictReader(f.readlines(), fieldnames=fieldnames, skipinitialspace=True)) with open('products.txt', 'r') as d: fieldnames = ('BikeID', 'BikeName') products = list(csv.DictReader(d.readlines(), fieldnames=fieldnames, restkey='BikeParts', skipinitialspace=True))Data is now stored in OrderedDict-s and we can use brute force to iterate over data (bad idea, but we are strong). We can construct iteration in a such way that we will get UnboundLocalError if there is no match and use it to return 'Invalid ID'.
To get name from ID:
def get_name(ID): try: if ID.startswith('bike'): for row in products: if row['BikeID'] == ID: name = row['BikeName'] else: for row in parts: if row['PartID'] == ID: name = row['Partname'] return name except UnboundLocalError: return 'Invalid ID'To get cost of bike parts:
def parts_cost(bike_id): try: for row in products: if row['BikeID'] == bike_id: cost = 0 for item in row['BikeParts']: part_id, qty = item.split(':') for row in parts: if part_id == row['PartID']: cost += int(row['PartCost']) * int(qty) return cost except UnboundLocalError: return 'Invalid ID'As mentioned, it is brute force. One should not iterate over (all) rows again and again; should break out of loop if desired result is achieved; should keep nesting level manageable.
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy
Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.