【问题标题】:Java, Python - How to convert Java FlatMap into Python LinkedListJava, Python - 如何将 Java FlatMap 转换为 Python LinkedList
【发布时间】:2016-09-30 17:43:12
【问题描述】:

我正在通过线性规划来制定运输问题。我主要在网上搜索它并找到了code which is written in Java。但是,我必须用 Python 编写全部内容。我正在将它转换成 Python。我并不声称自己擅长 Java,也不擅长 Python。我试着转换了一下。一切都很好,但是我不知道如何转换下面的sn-p,它处理Java的LinkedLists和Stream函数。

static LinkedList<Shipment> matrixToList() {
    return stream(matrix)
            .flatMap(row -> stream(row))
            .filter(s -> s != null)
            .collect(toCollection(LinkedList::new));
}

如果您有兴趣了解我如何转换上面链接的 Java 代码,您可以在这里看到下面的 Shipment 类是我的(不完整的)Python 代码:

import sys

class TransportationProblem:

    demand = list()
    supply = list()
    costs = list(list())
    matrix = list(list())

    def __init__(self):
        pass

    class Shipment:
        costPerUnit = 0.0
        quantity = 0.0
        r = 0
        c = 0

        def __init__(self, quantity, costPerUnit, r, c):
            self.quantity = quantity
            self.costPerUnit = costPerUnit
            self.r = r
            self.c = c

    def init(self, f_name= ""):
        try:
            with open(f_name) as f:
                val = [int(x) for x in f.readline().strip().split(' ')]
                numSources, numDestinations = val[0], val[1]
                src = list()
                dst = list()

                val = [int(x) for x in f.readline().strip().split(' ')]
                for i in range(0,numSources):
                    src.append(val[i])

                val = [int(x) for x in f.readline().strip().split(' ')]
                for i in range(0, numDestinations):
                    dst.append(val[i])

                totalSrc = sum(src)
                totalDst = sum(dst)

                if totalSrc > totalDst:
                    dst.append(totalSrc - totalDst)
                elif totalDst > totalSrc:
                    src.append(totalDst - totalSrc)

                self.supply = src
                self.demand = dst

                self.costs = [[0 for j in range(len(dst))] for i in range(len(src))]
                self.matrix = [[self.Shipment() for j in range(len(dst))] for i in range(len(src))]

                for i in range(0,len(src)):
                    val = [int(x) for x in f.readline().strip().split(' ')]
                    for j in range(0, len(dst)):
                        self.costs[i][j] = val[j]

                print self.costs
        except IOError:
            print "Error: can\'t find file or read data"

    def northWestCornerRule(self):
        northwest = 0
        for r in range(0, len(self.supply)):
            for c in range(northwest, len(self.demand)):
                quantity = min(self.supply[r], self.demand[c])
                if quantity > 0:
                    self.matrix[r][c] = self.Shipment(quantity=quantity, costPerUnit=self.costs[r][c], r=r, c=c)
                    self.supply[r] = self.supply[r] - quantity
                    self.demand[c] = self.demand[c] - quantity
                    if self.supply[r] == 0:
                        northwest = c
                        break

    def steppingStone(self):
        maxReduction = 0
        move = []
        leaving = self.Shipment()

        self.fixDegenerateCase()
        for r in range(0,len(self.supply)):
            for c in range(0,len(self.demand)):
                if self.matrix[r][c] != None:
                    pass

                trail = self.Shipment(quantity=0, costPerUnit=self.costs[r][c], r=r, c=c)
                path = self.geClosedPath(trail)

                reduction = 0
                lowestQuantity = sys.maxint
                leavingCandidate = None

                plus = True
                for s in path:
                    if plus == True:
                        reduction = reduction + s.costPerUnit
                    else:
                        reduction = reduction - s.costPerUnit
                        if s.quantity < lowestQuantity:
                            leavingCandidate = s
                            lowestQuantity = s.quantity
                    plus = not plus
                if reduction < maxReduction:
                    move = path
                    leaving = leavingCandidate
                    maxReduction = reduction

        if move != None:
            q = leaving.quantity
            plus = True
            for s in move:
                s.quantity = s.quantity + q if plus else s.quantity - q
                self.matrix[s.r][s.c] = None if s.quantity == 0 else s
                plus = not plus
            self.steppingStone()

    def fixDegenerateCase(self):
        pass

    def getClosedPath(self):
        pass

    def matrixToList(self):
        pass

【问题讨论】:

    标签: java python-2.7 linked-list code-conversion flatmap


    【解决方案1】:

    我们可以把它分成几个步骤。你从一个matrix 变量开始,它是一些包含Shipment 类型的迭代的迭代。

    流式传输对象意味着您对流的每个元素执行操作。

    流上的map 意味着您获取每个对象,例如A 类型,并将其转换为某种类型BflatMap 是在 map 将产生 Stream&lt;B&gt; 时使用的特殊情况。 flatMap 允许您将这些流连接成一个流。

    假设每个 A 映射到一个由 3 个对象组成的流 {A1, A2} -&gt; {{B11, B12, B13}, {B21, B22, B23}}

    flatMap 将制作这一流{A1, A2} -&gt; {B11, B12, B13, B21, B22, B23}

    在这种情况下,matrix 会生成 row 对象流。每个row 都映射到Shipment 的流中,flatMap 用于连接它们。

    最后filter用于去除空货(即值为null),调用collect方法将Shipment的流转化为List

    在没有流的情况下重新创建它可能如下所示:

    static LinkedList<Shipment> matrixToList() {
        LinkedList<Shipment> result = new LinkedList<>();
        for (List<Shipment> row : matrix) {
            for (Shipment shipment : row) {
                if (shipment != null) {
                    result.add(shipment );
                }
            }
        }
        return result;
    }
    

    【讨论】:

      猜你喜欢
      • 2021-05-09
      • 2014-05-14
      • 2018-06-11
      • 2016-12-14
      • 1970-01-01
      • 1970-01-01
      • 2022-01-14
      • 2019-08-28
      • 2011-10-27
      相关资源
      最近更新 更多