# 変数を定義する x = LpVariable.dicts('x', [(u, s) for u in users for s in songs], cat='Binary')
# 目的関数を定義する prob += lpSum([x[(u, s)] * ratings[(u, s)] for u in users for s in songs])
# 制約条件を追加する for u in users: prob += lpSum([x[(u, s)] for s in songs]) <= len(songs) // 2, f"User {u} - Song count" prob += lpSum([x[(u, s)] * ratings[(u, s)] for s in songs]) >= 3, f"User {u} - Minimum rating" prob += lpSum([x[(u, s)] * ratings[(u, s)] for s in songs]) <= 5, f"User {u} - Maximum rating" prob += lpSum([x[(u, s)] * ratings[(u, s)] for s in songs]) * 5 <= time_limits[u], f"User
[実行結果]
Status: Optimal
Total rating: 12.0
User 1 recommendations: ['Song 1']
User 2 recommendations: ['Song 4']
User 3 recommendations: ['Song 3']
User 4 recommendations: ['Song 2']
# 制約条件を定義 problem += p1 + p2 >= 150, 'Demand' problem += p1 <= 100, 'Capacity of Plant 1' problem += p2 <= 50, 'Capacity of Plant 2'
# 問題を解く problem.solve()
# 結果を出力 print(f'Optimal solution found with total cost of {problem.objective.value():.2f}') print(f'Plant 1 generates {p1.value()} MW') print(f'Plant 2 generates {p2.value()} MW')
# 目的関数を設定する prob += pulp.lpSum([weights[a] * returns[a] for a in assets])
# 制約条件を設定する prob += pulp.lpSum([weights[a] for a in assets]) == 1 prob += pulp.lpSum([weights[a] * risks[a] for a in assets]) <= 0.06
# 最適化問題を解く prob.solve()
# 結果を表示する print('Optimal Portfolio:') for a in assets: print('{}: {:.2%}'.format(a, weights[a].value()))
print('Expected Return: {:.2%}'.format(pulp.value(prob.objective))) print('Risk: {:.2%}'.format(pulp.lpSum([weights[a] * risks[a] for a in assets]).value()))