Tugas Logika algoritma
Asalamualaikum warohmatuloh wabarokatuh,
Sebelum memulei materi izinkan saya memperkenalkan diri terlrbih dahulu
Henry susanto - 17250140
Andika prasetya - 17250350
Berkat gumano - 17250276
Dejavu putri eren - 17250066
Zulfan arif maulana - 17250267
Pada pertemuan kali ini kami akan membuat program penyelesaian knapseck python
Kode python :
Script kodingan python :
# Program penyelesaian Fractional Knapsack dengan algoritma Greedy
def fractional_knapsack(value, weight, capacity):
index = list(range(len(value)))
ratio = [v / w for v, w in zip(value, weight)]
index.sort(key=lambda i: ratio[i], reverse=True)
max_value = 0
fractions = [0] * len(value)
for i in index:
if weight[i] <= capacity:
fractions[i] = 1
max_value += value[i]
capacity -= weight[i]
else:
fractions[i] = capacity / weight[i]
max_value += value[i] * (capacity / weight[i])
break
return max_value, fractions
n = int(input("Enter number of items: "))
value = input(f"Enter the values of the {n} item(s) in order: ").split()
value = [int(v) for v in value]
weight = input(f"Enter the positive weights of the {n} item(s) in order: ").split()
weight = [int(w) for w in weight]
capacity = int(input("Enter maximum weight: "))
max_value, fractions = fractional_knapsack(value, weight, capacity)
print("The maximum value of items that can be carried:", max_value)
print("The fractions in which the items should be taken:", fractions)
Output program :
Demikian materi yang kami sampaikan semoga bermanfaat
Wasalamualaikum warohmatuloh wabarokatu,



Komentar
Posting Komentar