0

I am working on an algorithm that is related to the Transportation Problem, originally written in Java. You can see the source code here. I have to convert it into Python.

In the linked source above, there is a function getClosedPath(...)

static Shipment[] getClosedPath(Shipment s) {
    LinkedList<Shipment> path = matrixToList();
    path.addFirst(s);

    // remove (and keep removing) elements that do not have a
    // vertical AND horizontal neighbor
    while (path.removeIf(e -> {
        Shipment[] nbrs = getNeighbors(e, path);
        return nbrs[0] == null || nbrs[1] == null;
    }));

    // place the remaining elements in the correct plus-minus order
    Shipment[] stones = path.toArray(new Shipment[path.size()]);
    Shipment prev = s;
    for (int i = 0; i < stones.length; i++) {
        stones[i] = prev;
        prev = getNeighbors(prev, path)[i % 2];
    }
    return stones;
}

I have converted it in Python as follows:

def getClosedPath(self, _shipment):
    path = linked_list.LinkedList()
    path.insert(_shipment)

    for e in range(0,path.size()):
        nbrs = self.getNeighbors(path[e], path)
        if nbrs[0] != None and nbrs[1] != None:
            path.delete(path[e])

    stones = []
    prev = _shipment
    for i in range(0, path.size()):
        stones.append(prev)
        prev = self.getNeighbors(prev, path)[i %2]
    return stones

It is giving me a valid error at nbrs = self.getNeighbors(path[e], path) i.e. TypeError: 'LinkedList' object does not support indexing.

No issues, I am well aware of the fact that LinkedList doesn't support indexing. I don't know Python much, thus I found a Python class for LinkedList available here at GitHub, it doesn't have any traversing methods.

Any idea how can I convert the above Java method into Python?

  • Does it specifically need to be a linked list? – Dave Newton Oct 04 '16 at 14:40
  • Actually, I have to convert [this](https://rosettacode.org/wiki/Transportation_problem#Java) code written in Jave into Python. It has an extensive usage of Linked-List, thus I (found myself) compelled to follow it. I will be glad if you propose any way without Linked List. – Muhammad Yaseen Khan Oct 04 '16 at 14:44
  • I'm asking why it's a linked list and not some other list implementation. I mean, Python isn't so hard you can't figure out some options-including extending a list implementation to do what you need if existing packages don't. But if you need indexing it doesn't seem like a linked list would be optimal. – Dave Newton Oct 04 '16 at 14:47
  • How could I do it without liked list – Muhammad Yaseen Khan Oct 04 '16 at 14:49
  • A list is an ordered collection. The question is why would a different ordered collection not work. – Dave Newton Oct 04 '16 at 14:59

0 Answers0