fork download
  1. from mpi4py import MPI
  2. import random
  3.  
  4. def generate_partial_results(num_parties):
  5. """
  6. Simulates the generation of partial results for each voting center.
  7. Returns a dictionary where keys are party names and values are the number of votes for each party.
  8. """
  9. partial_results = {}
  10. for i in range(num_parties):
  11. party_name = f"Party_{i+1}"
  12. votes = random.randint(100, 1000) # Randomly generate number of votes for each party
  13. partial_results[party_name] = votes
  14. return partial_results
  15.  
  16. def centralize_results(partial_results_list):
  17. """
  18. Centralizes the partial results from all voting centers to compute the total number of votes for each party.
  19. Returns a dictionary where keys are party names and values are the total number of votes for each party.
  20. """
  21. total_results = {}
  22. for partial_results in partial_results_list:
  23. for party, votes in partial_results.items():
  24. total_results[party] = total_results.get(party, 0) + votes
  25. return total_results
  26.  
  27. if __name__ == "__main__":
  28. comm = MPI.COMM_WORLD
  29. rank = comm.Get_rank()
  30. size = comm.Get_size()
  31.  
  32. num_parties = 5
  33. num_voting_centers = 3
  34.  
  35. if rank == 0:
  36. # Simulate partial results from each voting center
  37. partial_results_list = []
  38. for _ in range(num_voting_centers):
  39. partial_results = generate_partial_results(num_parties)
  40. partial_results_list.append(partial_results)
  41.  
  42. # Gather partial results from all voting centers
  43. all_partial_results = comm.gather(partial_results_list, root=0)
  44.  
  45. # Centralize results
  46. total_results = centralize_results([partial_results for partial_results_list in all_partial_results for partial_results in partial_results_list])
  47.  
  48. # Print total results
  49. print("Total Results:")
  50. for party, votes in total_results.items():
  51. print(f"{party}: {votes} votes")
  52. else:
  53. # Simulate partial results from each voting center
  54. partial_results = generate_partial_results(num_parties)
  55.  
  56. # Send partial results to the root process
  57. comm.gather(partial_results, root=0)
  58.  
  59. MPI.Finalize()
Success #stdin #stdout #stderr 0.29s 40592KB
stdin
Standard input is empty
stdout
Standard output is empty
stderr
Error: unexpected symbol in "from mpi4py"
Execution halted