from mpi4py import MPI
import random
def generate_partial_results(num_parties):
"""
Simulates the generation of partial results for each voting center.
Returns a dictionary where keys are party names and values are the number of votes for each party.
"""
partial_results = {}
for i in range(num_parties):
party_name = f"Party_{i+1}"
votes = random.randint(100, 1000) # Randomly generate number of votes for each party
partial_results[party_name] = votes
return partial_results
def centralize_results(partial_results_list):
"""
Centralizes the partial results from all voting centers to compute the total number of votes for each party.
Returns a dictionary where keys are party names and values are the total number of votes for each party.
"""
total_results = {}
for partial_results in partial_results_list:
for party, votes in partial_results.items():
total_results[party] = total_results.get(party, 0) + votes
return total_results
if __name__ == "__main__":
comm = MPI.COMM_WORLD
rank = comm.Get_rank()
size = comm.Get_size()
num_parties = 5
num_voting_centers = 3
if rank == 0:
# Simulate partial results from each voting center
partial_results_list = []
for _ in range(num_voting_centers):
partial_results = generate_partial_results(num_parties)
partial_results_list.append(partial_results)
# Gather partial results from all voting centers
all_partial_results = comm.gather(partial_results_list, root=0)
# Centralize results
total_results = centralize_results([partial_results for partial_results_list in all_partial_results for partial_results in partial_results_list])
# Print total results
print("Total Results:")
for party, votes in total_results.items():
print(f"{party}: {votes} votes")
else:
# Simulate partial results from each voting center
partial_results = generate_partial_results(num_parties)
# Send partial results to the root process
comm.gather(partial_results, root=0)
MPI.Finalize()