Certainly! Below is the corrected and complete Python code that addresses the issues in your original implementation. The primary fixes include:
- Import Statements: Added necessary imports such as
sys, deque, defaultdict, and heapq.
- Input Processing: Modified the input reading mechanism to handle inputs from standard input correctly.
- Pathfinding Enhancement: Replaced the BFS approach with Dijkstra's algorithm to prioritize paths with the least number of inter-parent transitions, ensuring minimal transaction costs.
- Edge Cases Handling: Added checks to ensure that demands can be fully met and that surplus can be appropriately handled by moving to TRIPARTY accounts.
- Clean Output: Ensured that the output is sorted as per the requirements and that quantities are positive integers.
Here's the complete code:
import sys
from collections import defaultdict, deque
import heapq
def main():
import sys
from collections import defaultdict, deque
import heapq
input_lines = [line.strip() for line in sys.stdin if line.strip()]
idx = 0
# Read number of stocks
n_stocks = int(input_lines[idx]); idx +=1
stock_prices = {}
for _ in range(n_stocks):
parts = input_lines[idx].split(',')
stock_id = parts[0].strip()
price = float(parts[1].strip())
stock_prices[stock_id] = price
idx +=1
# Read number of accounts
n_accounts = int(input_lines[idx]); idx +=1
accounts = {}
parent_accounts = {}
account_types = {}
for _ in range(n_accounts):
parts = input_lines[idx].split(',')
acc_id = parts[0].strip()
acc_type = parts[1].strip()
parent = parts[2].strip()
accounts[acc_id] = {'type': acc_type, 'parent': parent}
parent_accounts[acc_id] = parent
account_types[acc_id] = acc_type
idx +=1
# Read number of eligible accounts per stock
n_eligible_accounts = int(input_lines[idx]); idx +=1
stock_eligible_accounts = defaultdict(set)
for _ in range(n_eligible_accounts):
parts = input_lines[idx].split(',')
stock_id = parts[0].strip()
acc_id = parts[1].strip()
stock_eligible_accounts[stock_id].add(acc_id)
idx +=1
# Read number of eligible flows per stock
n_flows = int(input_lines[idx]); idx +=1
stock_flows = defaultdict(list)
for _ in range(n_flows):
parts = input_lines[idx].split(',')
stock_id = parts[0].strip()
src = parts[1].strip()
dst = parts[2].strip()
stock_flows[stock_id].append( (src, dst) )
idx +=1
# Read number of balances
n_balances = int(input_lines[idx]); idx +=1
stock_balances = defaultdict(lambda: defaultdict(int))
for _ in range(n_balances):
parts = input_lines[idx].split(',')
stock_id = parts[0].strip()
acc_id = parts[1].strip()
quantity = int(parts[2].strip())
stock_balances[stock_id][acc_id] += quantity # In case multiple entries
idx +=1
movements = defaultdict(int) # key: (stock_id, src, dst), value: qty
for stock_id in stock_prices:
eligible_accounts = stock_eligible_accounts[stock_id]
flows = stock_flows[stock_id]
# Build adjacency list
adj = defaultdict(list)
for src, dst in flows:
adj[src].append(dst)
# Identify excess and demand
excess = {}
demand = {}
for acc in eligible_accounts:
qty = stock_balances[stock_id].get(acc,0)
if qty >0:
excess[acc] = qty
elif qty <0:
demand[acc] = -qty
# Function to find path using Dijkstra with least inter_parent transitions
def find_path(src, dst):
heap = []
heapq.heappush(heap, (0, 0, src, [src])) # (inter_parent, path_length, current, path)
visited = {}
while heap:
inter_parent, path_length, current, path = heapq.heappop(heap)
if current == dst:
return path
if current in visited:
if (inter_parent, path_length) >= visited[current]:
continue
visited[current] = (inter_parent, path_length)
for neighbor in adj[current]:
new_inter_parent = inter_parent
if parent_accounts[current] != parent_accounts[neighbor]:
new_inter_parent +=1
new_path_length = path_length +1
heapq.heappush(heap, (new_inter_parent, new_path_length, neighbor, path + [neighbor]))
return None # No path found
# Fulfill demands
for d_acc, d_qty in demand.items():
# Find all possible surplus accounts that can reach d_acc
possible_sources = []
for s_acc, s_qty in excess.items():
path = find_path(s_acc, d_acc)
if path:
# Calculate inter-parent transitions
inter_parent = 0
for i in range(len(path)-1):
if parent_accounts[path[i]] != parent_accounts[path[i+1]]:
inter_parent +=1
possible_sources.append( (inter_parent, len(path), s_acc, path) )
# Sort sources by least inter_parent, then shortest path
possible_sources.sort()
needed = d_qty
for inter_parent, path_length, s_acc, path in possible_sources:
if needed ==0:
break
if s_acc not in excess or excess[s_acc]==0:
continue
available = excess[s_acc]
move_qty = min(available, needed)
# Record movement steps
for i in range(len(path)-1):
src = path[i]
dst = path[i+1]
movements[(stock_id, src, dst)] += move_qty
# Update surplus and demand
excess[s_acc] -= move_qty
needed -= move_qty
if needed >0:
# Cannot fulfill demand fully; depending on requirements, handle accordingly
# For this problem, we assume demands can be fully fulfilled
pass
# Handle remaining excess by moving to TRIPARTY accounts
triparty_accounts = [acc for acc in eligible_accounts if account_types[acc]=='TRIPARTY']
if triparty_accounts:
for s_acc, s_qty in list(excess.items()):
if s_qty <=0:
continue
# Find paths to any triparty account
possible_paths = []
for t_acc in triparty_accounts:
path = find_path(s_acc, t_acc)
if path:
# Calculate inter-parent transitions
inter_parent = 0
for i in range(len(path)-1):
if parent_accounts[path[i]] != parent_accounts[path[i+1]]:
inter_parent +=1
possible_paths.append( (inter_parent, len(path), t_acc, path) )
if possible_paths:
# Choose the path with least inter_parent transitions and shortest path
possible_paths.sort()
_, _, chosen_t_acc, chosen_path = possible_paths[0]
move_qty = s_qty
for i in range(len(chosen_path)-1):
src = chosen_path[i]
dst = chosen_path[i+1]
movements[(stock_id, src, dst)] += move_qty
# Update excess
excess[s_acc] -= move_qty
if excess[s_acc] ==0:
del excess[s_acc]
else:
# No path to any triparty account; handle accordingly (ignored for this problem)
pass
# Prepare and sort movements
final_movements = []
for (stock_id, src, dst), qty in movements.items():
if qty >0:
final_movements.append( (stock_id, src, dst, qty) )
# Sort by stock_id, src_account, dst_account
final_movements.sort(key=lambda x: (x[0], x[1], x[2]))
# Print movements
for move in final_movements:
print(','.join([move[0], move[1], move[2], str(move[3])]))
if __name__ == "__main__":
main()
Explanation of Fixes and Enhancements:
-
Imports Added:
sys: For reading standard input.
deque and defaultdict from collections: For efficient data handling.
heapq: For implementing the priority queue in Dijkstra's algorithm.
-
Input Reading Mechanism:
- The input is read from
stdin and stripped of any leading/trailing whitespace.
- An index
idx is used to traverse the input lines sequentially.
-
Pathfinding with Dijkstra's Algorithm:
- The
find_path function now uses Dijkstra's algorithm to find the path with the least number of inter-parent transitions.
- This ensures that the paths chosen incur minimal transaction costs by preferring intra-parent movements.
-
Movement Recording:
- Movements are recorded in the
movements dictionary with keys as tuples (stock_id, src, dst) and values as the quantity to move.
- This ensures that multiple movements between the same source and destination for a stock are aggregated.
-
Handling Remaining Excess:
- After fulfilling all demands, any remaining excess is moved to TRIPARTY accounts.
- The algorithm ensures that if multiple TRIPARTY accounts are available, the path with the least inter-parent transitions is chosen.
-
Final Output Sorting:
- The
final_movements list is sorted based on stock_id, source account, and destination account to meet the output format requirements.
-
Assumptions:
- It's assumed that all demands can be fully met with the available excess.
- If demands cannot be fully met, the code currently does not handle partial fulfillment but can be extended if needed.
Testing with Sample Input:
You can test the above code using the provided sample input. Save the code in a file, say stock_broker.py, and run it using Python. Provide the sample input when prompted or redirect a file containing the input.
Sample Input:
2
P1,2.5
P2,1.25
3
Loc1,CUSTODY,1
Loc2,CUSTODY,2
Loc3,TRIPARTY,2
6
P1,Loc1
P1,Loc2
P1,Loc3
P2,Loc1
P2,Loc2
P2,Loc3
7
P1,Loc1,Loc2
P1,Loc1,Loc3
P1,Loc2,Loc1
P1,Loc2,Loc3
P2,Loc1,Loc2
P2,Loc2,Loc3
P2,Loc3,Loc1
3
P1,Loc1,10
P1,Loc2,-5
P2,Loc1,5
Expected Output:
P1,Loc1,Loc2,5
P1,Loc1,Loc3,5
P2,Loc1,Loc2,5
P2,Loc2,Loc3,5
Running the corrected code with the above input should produce the expected output as specified.