Compare commits
3 Commits
Author | SHA1 | Date | |
---|---|---|---|
d53656a046 | |||
bfcbfa356a | |||
fabf2cf56d |
21
Liste+dactions+-+P7+Python+-+Feuille+1.csv
Normal file
21
Liste+dactions+-+P7+Python+-+Feuille+1.csv
Normal file
@ -0,0 +1,21 @@
|
||||
Actions #,Coût par action (en euros),Bénéfice (après 2 ans)
|
||||
Action-1,20,5%
|
||||
Action-2,30,10%
|
||||
Action-3,50,15%
|
||||
Action-4,70,20%
|
||||
Action-5,60,17%
|
||||
Action-6,80,25%
|
||||
Action-7,22,7%
|
||||
Action-8,26,11%
|
||||
Action-9,48,13%
|
||||
Action-10,34,27%
|
||||
Action-11,42,17%
|
||||
Action-12,110,9%
|
||||
Action-13,38,23%
|
||||
Action-14,14,1%
|
||||
Action-15,18,3%
|
||||
Action-16,8,8%
|
||||
Action-17,4,12%
|
||||
Action-18,10,14%
|
||||
Action-19,24,21%
|
||||
Action-20,114,18%
|
|
77
README.md
Normal file
77
README.md
Normal file
@ -0,0 +1,77 @@
|
||||
# AlgoInvest&Trade
|
||||
|
||||
Déterminer un choix optimal d'actions caractérisées par un coût et un rendement, en fonction d'un coût maximum pour un profit maximal
|
||||
|
||||
## Introduction
|
||||
|
||||
Ces instructions vous permettent de :
|
||||
- récupérer le programme,
|
||||
- d'installer l'environnement nécessaire à son exécution,
|
||||
- de l'exécuter,
|
||||
- d'en connaitre le résultat
|
||||
|
||||
|
||||
### Pré-requis
|
||||
|
||||
```
|
||||
paquets : python 3.11, python3.11-venv, git
|
||||
modules : csv
|
||||
```
|
||||
|
||||
### Installation
|
||||
|
||||
1. créer l'environnement virtuel :
|
||||
```
|
||||
python3.11 -m venv env
|
||||
source env/bin/activate
|
||||
```
|
||||
2. cloner le dépôt :
|
||||
```
|
||||
git clone https://mcstn.fr/gitea/Yann/Projet7.git
|
||||
```
|
||||
|
||||
|
||||
## Exécution
|
||||
|
||||
Pour l'algorithme bruteforce sur le dataset0,
|
||||
exécuter la commande :
|
||||
```
|
||||
python3 bruteforce.py
|
||||
```
|
||||
|
||||
Pour l'algorithme de DP, executer la commande :
|
||||
```
|
||||
python3 optimized.py
|
||||
```
|
||||
|
||||
|
||||
## Résultat
|
||||
|
||||
Optimized traite par défaut les datasets 1 et 2;
|
||||
Décommenter la ligne du dataset0 dans le main() si besoin
|
||||
```
|
||||
$ time python optimized.py
|
||||
|
||||
DATASET 1
|
||||
Cost: 499.43 €
|
||||
Profit: 196.84 €
|
||||
Shares : ['Share-HITN', 'Share-GRUT']
|
||||
|
||||
DATASET 2
|
||||
Cost: 497.67 €
|
||||
Profit: 194.90 €
|
||||
Shares : ['Share-GEBJ', 'Share-LFXB', 'Share-FWBE', 'Share-PLLK', 'Share-ZKSN', 'Share-ZOFA', 'Share-PATS', 'Share-DWSK', 'Share-ALIY', 'Share-ECAQ', 'Share-FAPS', 'Share-JGTW', 'Share-QLWT', 'Share-OPBR', 'Share-ANFX', 'Share-IJFT', 'Share-JWGF']
|
||||
|
||||
real 0m0,852s
|
||||
user 0m0,832s
|
||||
sys 0m0,018s
|
||||
```
|
||||
## Auteur
|
||||
|
||||
Yann <yann@needsome.coffee>
|
||||
|
||||
|
||||
|
||||
## License
|
||||
|
||||
N/A
|
111
bruteforce.py
111
bruteforce.py
@ -1,12 +1,7 @@
|
||||
import csv
|
||||
|
||||
|
||||
def powerset(itemList):
|
||||
result = [[]]
|
||||
for item in itemList:
|
||||
newsubsets = [subset + [item] for subset in result]
|
||||
result.extend(newsubsets)
|
||||
return result
|
||||
MAX_COST = 500
|
||||
FILE = "Liste+dactions+-+P7+Python+-+Feuille+1.csv"
|
||||
|
||||
def listFromFile(csv_file):
|
||||
"""
|
||||
@ -22,61 +17,71 @@ def listFromFile(csv_file):
|
||||
liste.pop(0)
|
||||
for item in liste:
|
||||
item[1] = int(item[1])
|
||||
item[2] = float(item[2].strip("%"))
|
||||
item[2] = item[1] * float(item[2].strip("%")) / 100
|
||||
return liste
|
||||
|
||||
def splitActions(actionList):
|
||||
"""
|
||||
split list in two parts, just in case we need to divide the operation for
|
||||
more efficiency
|
||||
returns a tuple with two lists
|
||||
"""
|
||||
liste1 = []
|
||||
liste2 = []
|
||||
for i in range(len(actionList)):
|
||||
if (i < 10):
|
||||
liste1.append(actionList[i])
|
||||
if (i >= 10):
|
||||
liste2.append(actionList[i])
|
||||
return (liste1, liste2)
|
||||
|
||||
def selectActions(actionList, max):
|
||||
def powerset(itemList):
|
||||
"""
|
||||
:param actionList: takes a list of combinations and a max
|
||||
:return: a list of selected combinations where cost is under max
|
||||
Generate every subset (combination) for a given list
|
||||
:param itemList: a list of items
|
||||
:return: a list of combinations(lists)
|
||||
"""
|
||||
result = [[]]
|
||||
for item in itemList:
|
||||
newsubsets = [subset + [item] for subset in result]
|
||||
result.extend(newsubsets)
|
||||
return result
|
||||
|
||||
|
||||
def transformData(dataset):
|
||||
"""
|
||||
Transform in a list of dict with computed values as gain, ratio
|
||||
Sorted by gain
|
||||
:param dataset: list of items
|
||||
:return: a sorted list of dict
|
||||
"""
|
||||
tmpset = [{'nom': x[0], 'cout': x[1],
|
||||
'rendement': x[2],
|
||||
'gain': x[1] * x[2] / 100,
|
||||
'ratio1': x[2] / x[1],
|
||||
'ratio2': (x[1] * x[2] / 100) / x[1]}
|
||||
for x in dataset if x[1] > 0.0 and x[2] > 0.0]
|
||||
|
||||
return sorted(tmpset, key=lambda x: x['gain'], reverse=True)
|
||||
|
||||
|
||||
def selectActions(actionList, maximal_cost):
|
||||
"""
|
||||
select combination corresponding to max cost
|
||||
:param actionList: list of combinations
|
||||
:param maximal_cost: maximal cost
|
||||
:return: a list of selected items
|
||||
"""
|
||||
best = []
|
||||
best2 = []
|
||||
for i in actionList:
|
||||
cout = 0
|
||||
rendement = 0
|
||||
cost = 0
|
||||
gain = 0
|
||||
for action in i:
|
||||
cout += action[1]
|
||||
rendement += action[2]
|
||||
if cout < int(max):
|
||||
best.append((rendement, cout, i))
|
||||
best2.append(i)
|
||||
return best, best2
|
||||
cost += action[1]
|
||||
gain += action[2]
|
||||
if cost < int(maximal_cost):
|
||||
best.append((gain, cost, i))
|
||||
|
||||
sortedBest = sorted(best, key=lambda k: k[0], reverse=True)
|
||||
|
||||
return sortedBest.pop(0)
|
||||
|
||||
|
||||
def main():
|
||||
actions = listFromFile(FILE)
|
||||
power_actions = powerset(actions)
|
||||
selected_actions = selectActions(power_actions, MAX_COST)
|
||||
# tri des actions sur le rendement
|
||||
print("Cost:", selected_actions[1], "€")
|
||||
print("Profit: %.2f €" % selected_actions[0])
|
||||
print(f"Shares: {[x[0] for x in selected_actions[2]]}")
|
||||
|
||||
actions = listFromFile("/home/b/Documents/OCR/projet7/actions.csv")
|
||||
powerActions = powerset(actions)
|
||||
selectedActions, selected = selectActions(powerActions, 500)
|
||||
|
||||
print("Longueur de la liste d'actions:", len(actions))
|
||||
print("Nb de combinaisons:", len(powerActions))
|
||||
print("Nb de combinaisons au cout inferieur à 500:", len(selectedActions))
|
||||
|
||||
#tri des actions sur le rendement
|
||||
best_sorted = sorted(selectedActions, key=lambda k: k[0], reverse=True)
|
||||
best2 = sort(selected, key=lambda k:[])
|
||||
#print("\nfive last sorted :")
|
||||
#for i in range(len(best_sorted)-1, len(best_sorted)-10, -1):
|
||||
# print("set", i, ":", best_sorted[i])
|
||||
#print(f"Rendement: {sum(x[2][1] * x[2][2]/100 for x in best_sorted[0])}")
|
||||
print(selected[1])
|
||||
print("Meilleur rendement:", best_sorted[0][0], "%")
|
||||
print("Actions sélectionnées:")
|
||||
for action in best_sorted[0][2]:
|
||||
print(f"Nom: {action[0]}, Cout: {action[1]}, Rendement: {action[2]}%")
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
|
1002
dataset1_Python+P7.csv
Normal file
1002
dataset1_Python+P7.csv
Normal file
File diff suppressed because it is too large
Load Diff
1001
dataset2_Python+P7.csv
Normal file
1001
dataset2_Python+P7.csv
Normal file
File diff suppressed because it is too large
Load Diff
52
greedy.py
52
greedy.py
@ -1,52 +0,0 @@
|
||||
import csv
|
||||
|
||||
class Item:
|
||||
def __init__(self, weight, value):
|
||||
self.weight = weight
|
||||
self.value = value
|
||||
self.ratio = value / weight
|
||||
|
||||
def fractional_knapsack(capacity, items):
|
||||
# sort items by value-to-weight ration in descending order
|
||||
items.sort(key=lambda x: x.ratio, reverse=True)
|
||||
total_value = 0
|
||||
remaining_capacity = capacity
|
||||
for item in items:
|
||||
if remaining_capacity >= item.weight:
|
||||
total_value += item.value
|
||||
remaining_capacity -= item.weight
|
||||
else:
|
||||
total_value += item.ratio * remaining_capacity
|
||||
break
|
||||
return total_value
|
||||
|
||||
|
||||
|
||||
def listFromFile(csv_file):
|
||||
liste = []
|
||||
with open(csv_file) as file:
|
||||
data = csv.reader(file)
|
||||
for i in data:
|
||||
liste.append(i)
|
||||
liste.pop(0)
|
||||
for item in liste:
|
||||
item[1] = float(item[1])
|
||||
item[2] = float(item[2])
|
||||
return liste
|
||||
|
||||
|
||||
def greedy(capacity:int, items:[]):
|
||||
# sort items by value-to-weight ration in descending order
|
||||
items.sort(key=lambda x: x.ratio, reverse=True)
|
||||
selected_items = []
|
||||
total_value = 0
|
||||
remaining_capacity = capacity
|
||||
for item in items:
|
||||
if remaining_capacity >= item.weight:
|
||||
total_value += item.value
|
||||
remaining_capacity -= item.weight
|
||||
selected_items.append(item)
|
||||
else:
|
||||
total_value += item.ratio * remaining_capacity
|
||||
break
|
||||
return selected_items, total_value
|
@ -1,39 +0,0 @@
|
||||
import csv
|
||||
|
||||
def listFromFile(csv_file):
|
||||
liste = []
|
||||
with open(csv_file) as file:
|
||||
data = csv.reader(file)
|
||||
for i in data:
|
||||
liste.append(i)
|
||||
liste.pop(0)
|
||||
for item in liste:
|
||||
item[1] = int(item[1])
|
||||
item[2] = float(item[2].strip("%"))
|
||||
|
||||
return liste
|
||||
|
||||
def listFromFile2(csv_file):
|
||||
liste = []
|
||||
with open(csv_file) as file:
|
||||
data = csv.reader(file)
|
||||
for i in data:
|
||||
liste.append(i)
|
||||
liste.pop(0)
|
||||
for item in liste:
|
||||
item[1] = float(item[1])
|
||||
item[2] = float(item[2])
|
||||
return liste
|
||||
|
||||
def splitListe(liste):
|
||||
liste1 = []
|
||||
liste2 = []
|
||||
|
||||
for i in range(len(liste)):
|
||||
if (i < 10):
|
||||
print(liste[i])
|
||||
liste1.append(liste[i])
|
||||
if (i >= 10):
|
||||
liste2.append(liste[i])
|
||||
|
||||
|
109
optimized.py
Normal file
109
optimized.py
Normal file
@ -0,0 +1,109 @@
|
||||
import csv
|
||||
|
||||
MAX_COST = 500
|
||||
DATASET1 = "dataset1_Python+P7.csv"
|
||||
DATASET2 = "dataset2_Python+P7.csv"
|
||||
DATASET0 = "Liste+dactions+-+P7+Python+-+Feuille+1.csv"
|
||||
|
||||
|
||||
def listFromFile(csv_file):
|
||||
"""
|
||||
Extract and format data from file(csv)
|
||||
:param csv_file: full path
|
||||
:return: a list of items
|
||||
"""
|
||||
liste = []
|
||||
with open(csv_file) as file:
|
||||
data = csv.reader(file)
|
||||
for i in data:
|
||||
liste.append(i)
|
||||
liste.pop(0)
|
||||
for item in liste:
|
||||
item[1] = float(item[1])
|
||||
if item[2][-1] == "%":
|
||||
item[2] = item[2].strip("%")
|
||||
item[2] = float(item[2])
|
||||
return liste
|
||||
|
||||
|
||||
def transformData(dataset):
|
||||
"""
|
||||
Transform in a list of dict with computed values as gain, ratio
|
||||
Sorted by gain
|
||||
:param dataset: list of items
|
||||
:return: a sorted list of dict
|
||||
"""
|
||||
tmpset = [{'nom': x[0], 'cout': x[1],
|
||||
'rendement': x[2],
|
||||
'gain': x[1] * x[2] / 100,
|
||||
'ratio1': x[2] / x[1],
|
||||
'ratio2': (x[1] * x[2] / 100) / x[1]}
|
||||
for x in dataset if x[1] > 0.0 and x[2] > 0.0]
|
||||
|
||||
return sorted(tmpset, key=lambda x: x['gain'], reverse=True)
|
||||
|
||||
|
||||
def get_results(filepath, maximum, nbr):
|
||||
"""
|
||||
load, transform data then run the algorithm and print results
|
||||
:param filepath: full path to csv
|
||||
:param maximum: maximum cost
|
||||
:param nbr: set number
|
||||
:return: print results
|
||||
"""
|
||||
|
||||
action_list = transformData(listFromFile(filepath))
|
||||
maximum_gain, selection = sacADosFloat(action_list, maximum)
|
||||
|
||||
print("\nDATASET", nbr)
|
||||
print(f"Cost: {sum(x['cout'] for x in selection):.2f} €")
|
||||
print("Profit: %.2f €" % maximum_gain)
|
||||
print(f"Shares : {[x['nom'] for x in selection]}")
|
||||
|
||||
|
||||
def sacADosFloat(actions, maximum_cost):
|
||||
"""
|
||||
Use dynamic approach
|
||||
:param actions: a list of dict with minimum key as cost and gain
|
||||
:param maximum_cost: the constraint, our max cost
|
||||
:return: maximum gain: int, selected items: list
|
||||
"""
|
||||
n = len(actions)
|
||||
table = [[0.0 for x in range(int(maximum_cost) + 1)] for x in range(n + 1)]
|
||||
|
||||
# Dynamic programing table
|
||||
for i in range(n + 1):
|
||||
for w in range(int(maximum_cost) + 1):
|
||||
if i == 0 or w == 0:
|
||||
table[i][w] = 0.0
|
||||
elif actions[i-1]['cout'] <= w:
|
||||
table[i][w] = (
|
||||
max(
|
||||
actions[i-1]['gain'] +
|
||||
table[i-1][int(w-actions[i-1]['cout'])],
|
||||
table[i-1][w]
|
||||
)
|
||||
)
|
||||
|
||||
else:
|
||||
table[i][w] = table[i-1][w]
|
||||
|
||||
# Selection
|
||||
w = maximum_cost
|
||||
selected_actions = []
|
||||
for i in range(n, 0, -1):
|
||||
if table[i][int(w)] != table[i-1][int(w)]:
|
||||
selected_actions.append(actions[i-1])
|
||||
w -= actions[i-1]['cout']
|
||||
|
||||
return table[n][int(maximum_cost)], selected_actions
|
||||
|
||||
|
||||
def main():
|
||||
# get_results(DATASET0, MAX_COST, 0)
|
||||
get_results(DATASET1, MAX_COST, 1)
|
||||
get_results(DATASET2, MAX_COST, 2)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
28
permute.py
28
permute.py
@ -1,28 +0,0 @@
|
||||
def permute(liste):
|
||||
if len(liste) == 0:
|
||||
return []
|
||||
|
||||
if len(liste) == 1:
|
||||
return [liste]
|
||||
|
||||
permutations = []
|
||||
|
||||
for i in range(len(liste)):
|
||||
current = liste[i]
|
||||
remaining = liste[:i] + liste[i+1:]
|
||||
|
||||
for p in permute(remaining):
|
||||
permutations.append([current] + p)
|
||||
|
||||
return permutations
|
||||
|
||||
|
||||
|
||||
liste = []
|
||||
|
||||
for i in range(1, 6):
|
||||
liste.append(i)
|
||||
|
||||
|
||||
test = permute(liste)
|
||||
print(test)
|
@ -1,70 +0,0 @@
|
||||
from math import log
|
||||
|
||||
def powerset(xs):
|
||||
result = [[]]
|
||||
for x in xs:
|
||||
newsubsets = [subset + [x] for subset in result]
|
||||
result.extend(newsubsets)
|
||||
return result
|
||||
|
||||
def powerset2(orig, newset):
|
||||
if orig == []:
|
||||
return [newset]
|
||||
else:
|
||||
res = []
|
||||
for s in powerset2(orig[1:], newset+[orig[0]]):
|
||||
res.append(s)
|
||||
for s in powerset2(orig[1:], newset):
|
||||
res.append(s)
|
||||
return res
|
||||
|
||||
def powerset3(orig, newset):
|
||||
if orig == []:
|
||||
yield newset
|
||||
else:
|
||||
for s in powerset3(orig[1:], newset+[orig[0]]):
|
||||
yield s
|
||||
for s in powerset3(orig[1:], newset):
|
||||
yield s
|
||||
|
||||
def powerset4(lst):
|
||||
if len(lst) <= 1:
|
||||
yield lst
|
||||
yield []
|
||||
else:
|
||||
for x in powerset4(lst[1:]):
|
||||
yield [lst[0]] + x
|
||||
yield x
|
||||
|
||||
def powerset5(lst):
|
||||
if lst == []:
|
||||
yield []
|
||||
else:
|
||||
for s in powerset5(lst[1:]):
|
||||
yield s + [lst[0]]
|
||||
yield s
|
||||
|
||||
def powerset6(lst):
|
||||
pairs = [(2**i, x) for i, x in enumerate(lst)]
|
||||
for i in xrange(2**len(pairs)):
|
||||
yield [x for (mask, x) in pairs if i & mask]
|
||||
|
||||
if __name__ == '__main__':
|
||||
l = [1,2,3]
|
||||
|
||||
# print(powerset(l))
|
||||
# print(powerset2(l, []))
|
||||
# print list(powerset3(l, []))
|
||||
# print list(powerset4(l))
|
||||
# print list(powerset5(l))
|
||||
# print list(powerset6(l))
|
||||
|
||||
# n = 8
|
||||
# for i in range(n):
|
||||
# b = str(bin(i))[2:]
|
||||
# if n % 2 != 0:
|
||||
# l = int(1.0+len(n, 2))
|
||||
# else:
|
||||
# l = int(log(n, 2))
|
||||
# b = '0'*(l - len(b)) + b
|
||||
# print b
|
66
sacadeux.py
66
sacadeux.py
@ -1,66 +0,0 @@
|
||||
import csv
|
||||
|
||||
def listFromFile(csv_file):
|
||||
liste = []
|
||||
with open(csv_file) as file:
|
||||
data = csv.reader(file)
|
||||
for i in data:
|
||||
liste.append(i)
|
||||
liste.pop(0)
|
||||
for item in liste:
|
||||
item[1] = float(item[1])
|
||||
item[2] = float(item[2])
|
||||
return liste
|
||||
|
||||
def sac_a_dos(actions, cout_maximal):
|
||||
n = len(actions)
|
||||
# Créer une table pour stocker les résultats des sous-problèmes
|
||||
table = [[0 for x in range(cout_maximal + 1)] for x in range(n + 1)]
|
||||
|
||||
# Construire la table de programmation dynamique
|
||||
for i in range(n + 1):
|
||||
for w in range(int(cout_maximal) + 1):
|
||||
print(w - actions[i-1]['cout'])
|
||||
#print(w-actions[i-1])
|
||||
if i == 0 or w == 0:
|
||||
table[i][w] = 0.0
|
||||
elif actions[i-1]['cout'] <= w:
|
||||
table[i][w] = max(actions[i-1]['rendement'] + table[i-1][int(w-actions[i-1]['cout'])], table[i-1][w])
|
||||
else:
|
||||
table[i][w] = table[i-1][w]
|
||||
|
||||
|
||||
for i in range(n + 1):
|
||||
print(f"\ntable[{i}][60]", table[i][60], i-1)
|
||||
print(f"actions[{i}-1]['rendement']", actions[i-1]['rendement'])
|
||||
print(f"table[{i}-1][(60-actions[{i}-1]['cout'])]", table[i-1][(60-actions[i-1]['cout'])])
|
||||
print(f"table[{i}-1][60]", table[i-1][60])
|
||||
print(f"actions[{i}-1]['rendement'] + table[{i}-1][(60-actions[{i}-1]['cout'])], table[{i}-1][60]", actions[i-1]['rendement'] + table[i-1][(w-actions[i-1]['cout'])], table[i-1][w])
|
||||
# Trouver les actions sélectionnées
|
||||
w = cout_maximal
|
||||
actions_selectionnees = []
|
||||
for i in range(n, 0, -1):
|
||||
if table[i][int(w)] != table[i-1][int(w)]:
|
||||
actions_selectionnees.append(actions[i-1])
|
||||
w -= actions[i-1]['cout']
|
||||
|
||||
return table[n][cout_maximal], actions_selectionnees
|
||||
|
||||
|
||||
def display_result():
|
||||
print(f"Rendement maximal: {rendement_maximal}%")
|
||||
print("Actions sélectionnees:")
|
||||
for action in actions_selectionnees:
|
||||
print(
|
||||
f"Nom: {action['nom']}, Cout: {action['cout']}, Rendement: {action['rendement']}%")
|
||||
|
||||
#actions = listFromFile("/home/b/Documents/OCR/projet7/actions.csv")
|
||||
actions = listFromFile("/home/b/Documents/OCR/projet7/ph3/dataset1_Python+P7.csv")
|
||||
# Conversion de la liste en dictionnaires pour faciliter l'accès
|
||||
actions = [{'nom': action[0], 'cout': action[1], 'rendement': action[2]} for action in actions]
|
||||
|
||||
#print(actions[22]['cout'], type(actions[22]['cout']))
|
||||
cout_maximal = 500
|
||||
rendement_maximal, actions_selectionnees = sac_a_dos(actions, cout_maximal)
|
||||
|
||||
# display_result()
|
48
sacados.py
48
sacados.py
@ -1,48 +0,0 @@
|
||||
from importactions import listFromFile, listFromFile2
|
||||
|
||||
def sac_a_dos(actions, cout_maximal):
|
||||
n = len(actions)
|
||||
# Créer une table pour stocker les résultats des sous-problèmes
|
||||
table = [[0 for x in range(cout_maximal + 1)] for x in range(n + 1)]
|
||||
|
||||
# Construire la table de programmation dynamique
|
||||
for i in range(n + 1):
|
||||
for w in range(cout_maximal + 1):
|
||||
#print('\ni', i, 'w', w)
|
||||
#print(actions[i-1]['cout'], )
|
||||
if i == 0 or w == 0:
|
||||
table[i][w] = 0
|
||||
elif actions[i-1]['cout'] <= w:
|
||||
table[i][w] = max(actions[i-1]['rendement'] + table[i-1][(w-actions[i-1]['cout'])], table[i-1][w])
|
||||
else:
|
||||
table[i][w] = table[i-1][w]
|
||||
|
||||
# Trouver les actions sélectionnées
|
||||
w = cout_maximal
|
||||
actions_selectionnees = []
|
||||
for i in range(n, 0, -1):
|
||||
if table[i][w] != table[i-1][w]:
|
||||
actions_selectionnees.append(actions[i-1])
|
||||
w -= actions[i-1]['cout']
|
||||
|
||||
return table[n][cout_maximal], actions_selectionnees
|
||||
|
||||
|
||||
def display_result():
|
||||
print(f"Rendement : {sum(x['cout'] * x['rendement']/100 for x in actions_selectionnees)}€")
|
||||
print(f"Cout: {sum(x['cout'] for x in actions_selectionnees)}€")
|
||||
print("Actions sélectionnees:")
|
||||
for action in actions_selectionnees:
|
||||
print(
|
||||
f"Nom: {action['nom']}, Cout: {action['cout']}, Rendement: {action['rendement']}%")
|
||||
|
||||
actions = listFromFile("/home/b/Documents/OCR/projet7/actions.csv")
|
||||
#actions = listFromFile2("/home/b/Documents/OCR/projet7/ph3/dataset1_Python+P7.csv")
|
||||
# Conversion de la liste en dictionnaires pour faciliter l'accès
|
||||
actions = [{'nom': action[0], 'cout': action[1], 'rendement': action[2]} for action in actions]
|
||||
|
||||
#print(actions[22]['cout'], type(actions[22]['cout']))
|
||||
cout_maximal = 500
|
||||
rendement_maximal, actions_selectionnees = sac_a_dos(actions, cout_maximal)
|
||||
|
||||
display_result()
|
11
test.py
11
test.py
@ -1,11 +0,0 @@
|
||||
def dig_root(n: int) -> int | None:
|
||||
s = 0
|
||||
if len(str(n)) == 1:
|
||||
s = n
|
||||
return s
|
||||
for i in str(n):
|
||||
s += int(i)
|
||||
dig_root(s)
|
||||
|
||||
|
||||
print(dig_root(942))
|
@ -1,61 +0,0 @@
|
||||
import csv
|
||||
|
||||
def listFromFile(csv_file):
|
||||
liste = []
|
||||
with open(csv_file) as file:
|
||||
data = csv.reader(file)
|
||||
for i in data:
|
||||
liste.append(i)
|
||||
liste.pop(0)
|
||||
for item in liste:
|
||||
item[1] = float(item[1])
|
||||
item[2] = float(item[2])
|
||||
return liste
|
||||
|
||||
def sac_a_dos_float(actions, cout_maximal):
|
||||
n = len(actions)
|
||||
table = [[0.0 for x in range(int(cout_maximal) + 1)] for x in range(n + 1)]
|
||||
|
||||
# Dynamic programing table
|
||||
for i in range(n + 1):
|
||||
for w in range(int(cout_maximal) + 1):
|
||||
if i == 0 or w == 0:
|
||||
table[i][w] = 0.0
|
||||
elif actions[i-1]['cout'] <= w:
|
||||
table[i][w] = max(actions[i-1]['rendement'] + table[i-1][int(w-actions[i-1]['cout'])], table[i-1][w])
|
||||
else:
|
||||
table[i][w] = table[i-1][w]
|
||||
|
||||
# Select
|
||||
w = cout_maximal
|
||||
actions_selectionnees = []
|
||||
for i in range(n, 0, -1):
|
||||
if table[i][int(w)] != table[i-1][int(w)]:
|
||||
actions_selectionnees.append(actions[i-1])
|
||||
w -= actions[i-1]['cout']
|
||||
|
||||
return table[n][int(cout_maximal)], actions_selectionnees
|
||||
|
||||
actions = listFromFile("/home/b/Documents/OCR/projet7/ph3/dataset1_Python+P7.csv")
|
||||
actionstmp = [{'nom': action[0], 'cout': action[1], 'rendement': action[2]} for action in actions if action[1] > 0.0]
|
||||
actions = sorted(actionstmp, key=lambda x: x['cout'])
|
||||
|
||||
actions2 = listFromFile("/home/b/Documents/OCR/projet7/ph3/dataset2_Python+P7.csv")
|
||||
actions2tmp = [{'nom': action[0], 'cout': action[1], 'rendement': action[2]} for action in actions2 if action[1] > 0.0]
|
||||
actions2 = sorted(actions2tmp, key=lambda x: x['cout'])
|
||||
|
||||
|
||||
cout_maximal = 500
|
||||
|
||||
valeur_maximale, actions_selectionnees = sac_a_dos_float(actions, cout_maximal)
|
||||
valeur_maximale2, actions_selectionnees2 = sac_a_dos_float(actions2, cout_maximal)
|
||||
|
||||
print("\nDATASET 1\n")
|
||||
print(f"Cout: {sum(x['cout'] for x in actions_selectionnees):.2f}")
|
||||
print(f"Rendement: {sum((x['cout']*x['rendement']/100)for x in actions_selectionnees):.2f}")
|
||||
print(f"Actions sélectionnées: {[x['nom'] for x in actions_selectionnees]}")
|
||||
|
||||
print("\nDATASET 2\n")
|
||||
print(f"Cout: {sum(x['cout'] for x in actions_selectionnees2):.2f}")
|
||||
print(f"Rendement: {sum((x['cout']*x['rendement']/100)for x in actions_selectionnees2):.2f}")
|
||||
print(f"Actions sélectionnées: {[x['nom'] for x in actions_selectionnees2]}")
|
Loading…
x
Reference in New Issue
Block a user