贪婪算法 python_在Python中使用贪婪算法进行优化

贪婪算法 python

In the real world, choosing the best option is an optimization problem and as a result, we have the best solution with us. In mathematics, optimization is a very broad topic which aims to find the best fit for the data/problem. Such optimization problems can be solved using the Greedy Algorithm ("A greedy algorithm is an algorithm that follows the problem-solving heuristic of making the locally optimal choice at each stage with the intent of finding a global optimum"). This is the Wikipedia definition and we find one of the optimum solutions by keeping constraints in mind. This is one of the simplest algorithms used for optimization.

在现实世界中,选择最佳选项是一个优化问题,因此,我们拥有最佳解决方案。 在数学中,优化是一个非常广泛的主题,旨在找到最适合数据/问题的方法。 可以使用贪婪算法 ( “贪心算法是遵循在每个阶段做出局部最优选择以寻求全局最优的意图的问题解决启发式 算法 ”)来解决此类优化问题。 这是Wikipedia的定义 ,我们通过牢记约束来找到最佳解决方案之一。 这是用于优化的最简单算法之一。

Let us consider a problem where Hareus gets 1500$ as pocket money. He is a hostler and needs to buy essentials for the month. So, he reserves 1000$ for essentials and now he has the rest of the 500$ for his spending. He went to the supermarket and there he had to decide what to buy according to the value(a measure of each item related to productivity) and also have a constraint of 500$. This is one of the optimization problems and the following is the code for choosing the items in one of the best ways.

让我们考虑一个问题,Hareus得到1500美元的零用钱。 他是一个招待员,需要购买该月的必需品。 因此,他保留了1000美元的必需品,现在剩下500美元中的其余钱用于他的支出。 他去了超市,在那里他不得不根据价值(与生产力相关的每个项目的度量)决定要买什么,并且还具有500 $的约束。 这是优化问题之一,以下是以最佳方式之一选择项目的代码。

Key Idea: Productivity Maximum with 500$.

关键思想:最高生产率为500 $。

Python Implementation:

Python实现:

# Greedy Algorithm for a Optimisation Problem

# Defined a class for item, 
# with its name, value and cost
class Itm(object):
    def __init__(self, name, val, cost):
        self.name = name
        self.val = val
        self.cost = cost
        
    def getvalue(self):
        return self.val
    
    def getcost(self):
        return self.cost
    
    def __str__(self):
        return self.name 
  
# Defining a function for building a List 
# which generates list of items that are 
# available at supermart   
def buildlist(names, values, costs):
    menu = []
    for i in range(len(names)):
        menu.append(Itm(names[i], values[i], costs[i]))
    return menu

# Implementation of greedy algorithm 
# to choose one of the optimum choice
def greedy(items, maxcal, keyfunction):
    itemscopy = sorted(items, key = keyfunction, reverse = True)
    
    result = []
    totalval = 0 
    totalcal = 0
    
    for i in range(len(items)):
        if (totalcal + itemscopy[i].getcost() <= maxcal):
            result.append(itemscopy[i])
            totalval = totalval + itemscopy[i].getvalue()
            totalcal = totalcal + itemscopy[i].getcost()
            
    return (result, totalval)


# Main Function
# All values are random    
names = ['Ball', 'Gloves', 'Notebook', 'Bagpack', 'Charger', 'Pillow', 'Cakes', 'Pencil']
values = [89,90,95,100,90,79,50,10]
costs = [123,154,25,145,365,150,95,195]
Itemrs = buildlist(names, values, costs)
maxcost = 500 # maximum money he have to spend

taken, totvalue = greedy(Itemrs, maxcost, Itm.getvalue)

print('Total vaule taken : ', totvalue)

# Printing the list of item slected for optimum value
for i in range(len(taken)):
    print('  ', taken[i])

Output

输出量

Total vaule taken :  374
   Bagpack
   Notebook
   Gloves
   Ball


翻译自: https://www.includehelp.com/python/optimization-using-greedy-algorithm.aspx

贪婪算法 python

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值