prometheus800

ВИ Лаб 2: Формирање на најдобар тим (CSP)

May 15th, 2021
681
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. from constraint import *
  2.  
  3.  
  4. def get_key(val, the_dict):
  5.     for k, v in the_dict.items():
  6.         if val == v:
  7.             return k
  8.  
  9.     return "no such key"
  10.  
  11.  
  12. if __name__ == '__main__':
  13.  
  14.     num_members = int(input())
  15.     members_dict = dict()
  16.     members_domain = list()
  17.     members_vars = [f'Participant {member + 1}' for member in range(5)]
  18.     for _ in range(num_members):
  19.         w, n = input().split(" ")
  20.         members_dict[n] = float(w)
  21.         members_domain.append(float(w))
  22.  
  23.     num_leaders = int(input())
  24.     leaders_dict = dict()
  25.     leaders_domain = list()
  26.     leaders_vars = ["Leader"]
  27.     for _ in range(num_leaders):
  28.         w, n = input().split(" ")
  29.         leaders_dict[n] = float(w)
  30.         leaders_domain.append(float(w))
  31.  
  32.     problem = Problem()
  33.  
  34.     problem.addVariables(leaders_vars, leaders_domain)
  35.  
  36.     problem.addVariables(members_vars, members_domain)
  37.  
  38.     problem.addConstraint(AllDifferentConstraint(), members_vars)
  39.  
  40.     problem.addConstraint(MaxSumConstraint(100))
  41.  
  42.     solutions = dict()
  43.  
  44.     for solution in problem.getSolutions():
  45.         total_weight = 0
  46.         for value in solution.values():
  47.             total_weight += value
  48.  
  49.         solutions[total_weight] = [value for value in solution.values()]
  50.  
  51.     best_team = max(solutions.keys())
  52.  
  53.     whole_team = solutions[best_team]
  54.  
  55.     best_leader = whole_team[-1]
  56.  
  57.     print(f'Total score: {round(best_team, 1)}')
  58.     print(f'Team leader: {get_key(best_leader, leaders_dict)}')
  59.  
  60.     del whole_team[-1]
  61.  
  62.     for i in range(len(whole_team)):
  63.         print(f'Participant {i + 1}: {get_key(whole_team[i], members_dict)}')
  64.        
  65.     ''' ---------- Sample input and ouput ----------    
  66.     Input       Result
  67.     10          Total score: 100.0
  68.     31.3 A      Team leader: O
  69.     28.4 B      Participant 1: J
  70.     26.1 C      Participant 2: I
  71.     24.2 D      Participant 2: I
  72.     21.8 E      Participant 3: H
  73.     20.3 F      Participant 4: F
  74.     15.5 G      Participant 5: B
  75.     14.1 H
  76.     12.5 I
  77.     11.5 J
  78.     5
  79.     32.2 K
  80.     27.4 L
  81.     24.6 M
  82.     14.9 N
  83.     13.2 O
  84.     '''
  85.  
  86.  
  87.  
  88.  
  89.  
  90.  
  91.  
RAW Paste Data