[note]Linear Programming

 

 # solves *bounded* LPs of the form:
        # max cx
        # sub to: Ax <= b
from sympy import *
from itertools import combinations
        # enumerates all the vertices of {x | Ax <= b}
def enumeratevertices(A, b):
    m, n = A.rows, A.cols     
    for rowlist in combinations(range(m), n):
        Ap = A.extract(rowlist, range(n))
        bp = b.extract(rowlist, [0])
        if Ap.det() != 0:
            xp = Ap.LUsolve(bp)
            d = A * xp - b
            feasible = True
            for i in range(m):
                if d[i] > 0:
                    feasible = False
            if feasible:
                yield xp       
        # finds the optimum using vertex enumeration
def findoptimum(A, b, c):
    m, n = A.rows, A.cols
    bestvalue, bestvertex = None, None
    for vertex in enumeratevertices(A, b):
        if bestvalue is None or (vertex.T*c)[0] > bestvalue:
            bestvalue = (vertex.T * c)[0]
            bestvertex = vertex
    return bestvertex
def solve(A, b, c):
    x = findoptimum(A, b, c)
    if not x:
        print 'LP is infeasible'
    else:
        print 'Vertex', x.T, 'is optimal'
        print 'Optimal value is', c.T*x
if __name__ == '__main__':
    A = Matrix([[-10,  -6, -9, -10],
                [  8,  -6, -5,  -5],
                [ -7,  -1, -9,   3],
                [ -1,  -4,  5,  10],
                [  1,   2,  0,  10],
                [  2,  -9,  3,  -8],
                [ -8,  -1, -8,   1],
                [  7, -10,  4,  -4],
                [-10,   2,  5,   8],
                [ -7,   9,  4,  -4],
                [ -1,   0,  0,   0],
                [  0,  -1,  0,   0],
                [  0,   0, -1,   0],
                [  0,   0,  0,  -1]])
    b = Matrix([9, 7, 3, 4, 8, 0, 3, 2, 4, 8, 0, 0, 0, 0])
    c = Matrix([2, -2, -3, 8])
    solve(A, b, c)
    

全部评论

相关推荐

Jcwemz:中软证书写单行,考了什么学了什么相关技术栈的内容就说自己会什么, 没实习就包装实习简历,将项目经历写成实习做的,项目时间拉长,项目成果具体化,测试的项目成果无非就是写了多少用例查出了多少bug,重要的不是实习了多久,而是你会多少东西,你能表达的就都是你的。 cet4,随便找个地方标上就好了,不用写单行。 粗略建议,我也不在行,觉得对的可以采纳
实习,投递多份简历没人回...
点赞 评论 收藏
分享
10-19 11:19
已编辑
哈尔滨理工大学 golang
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务