DEV Community

Durga Pokharel
Durga Pokharel

Posted on • Edited on

2 1

Day 59 Of 100DaysOfCode : More About Algorithm

This is my 59th day of #100daysofcode and #python learning like yesterday today also learned more properties of SQL (subquery inside where, subquery inside from) from datacamp. Also tried to slove assignment in coursera.

Here is a code for fractional knapsack

python code

# from https://www.tutorialspoint.com/program-to-implement-the-fractional-knapsack-problem-in-python
class FractionalKnapsack:
    def solve(self, weights, values, capacity):
        res = 0
        for pair in sorted(zip(weights, values), key=lambda x: - x[1]/x[0]):
            if not bool(capacity):
                break
            if pair[0] > capacity:
                res += int(pair[1] / (pair[0] / capacity))
                capacity = 0
            elif pair[0] <= capacity:
                res += pair[1]
                capacity -= pair[0]
        return int(res)

ob = FractionalKnapsack()
weights = [20, 50, 30]
values = [60, 100, 120]
capacity = 50
print(ob.solve(weights, values, capacity))
Enter fullscreen mode Exit fullscreen mode

Possible optimal solution will be,

180
Enter fullscreen mode Exit fullscreen mode

Day 59 Of #100DaysOfCode and #Python
* Fractional knapsack #DEVCommunity #womenintech #CodeNewbie pic.twitter.com/XIWlRYpoa4

— Durga Pokharel (@mathdurga) February 25, 2021

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay