Python客户账单计算系统实现作业问题及TypeError报错求助
Hey there! Let's fix that error first, then build the correct invoice calculation function that meets your test case requirements.
Why the Error Happens
The TypeError: unhashable type: 'dict' pops up because you're trying to convert lists of dictionaries (pricing and checks) into sets. Dictionaries are mutable objects in Python, so they can't be stored in sets (which require hashable, immutable elements). That set intersection approach won't work here—we need a simpler, more direct way to map check types to their prices.
Correct Solution Code
Here's a working implementation that passes your test cases:
pricing = [{"check_type": "document_photo", "price":0.5, "currency":"USD"}, {"check_type": "document_video", "price":0.9, "currency":"USD"}, {"check_type": "facial_similarity_photo", "price":0.3, "currency":"USD"}, {"check_type": "facial_similarity_video", "price":0.8, "currency":"USD"}, {"check_type": "right_to_work", "price":1.25, "currency":"USD"}] checks = [{"client": "ABC Bank", "check_type": "facial_similarity_video", "result": "pass"}, {"client": "ABC Bank", "check_type": "facial_similarity_video", "result": "fail"}, {"client": "XYCoin", "check_type": "document_photo", "result": "bad_input"}, {"client": "XYCoin", "check_type": "facial_similarity_photo", "result": "pass"}, {"client": "XYCoin", "check_type": "document_photo", "result": "pass"}] def calculate_invoice(client_name): # Create a fast lookup map: check type → price price_lookup = {entry['check_type']: entry['price'] for entry in pricing} total_amount = 0.0 for check_record in checks: # Only count checks for the target client, excluding bad_input results if check_record['client'] == client_name and check_record['result'] != 'bad_input': # Add the price for this check type to the total total_amount += price_lookup[check_record['check_type']] return total_amount # Verify the test cases print(calculate_invoice("ABC Bank")) # Output: 1.6 print(calculate_invoice("XYCoin")) # Output: 0.8
How This Works
- Price Lookup Map: We convert the
pricinglist into a dictionary (price_lookup) where each key is acheck_typeand the value is its corresponding price. This lets us look up prices instantly, which is way more efficient than searching the list every time. - Filter and Calculate: We loop through every check record:
- We only consider records that belong to the client we're invoicing.
- We skip any checks with a
bad_inputresult (since your test case shows these aren't charged). - For valid checks, we fetch the price from our lookup map and add it to the total.
Test Case Breakdown
- ABC Bank: Both checks are
facial_similarity_video($0.8 each), so 0.8 + 0.8 = 1.6. - XYCoin: We exclude the
bad_inputcheck, then adddocument_photo($0.5) andfacial_similarity_photo($0.3) → 0.5 + 0.3 = 0.8.
This matches exactly what your test cases require!
内容的提问来源于stack exchange,提问作者Nitesh
相关产品推荐
相关产品推荐

