Convert a LinkedList to a String in Python

[ad_1]

The problem

Preloaded for you is a category, struct, or derived information sort Node (relying on the language) used to assemble linked lists on this problem:

class Node():
    def __init__(self, information, subsequent = None):
        self.information = information
        self.subsequent = subsequent

Create a perform stringify which accepts an argument record/$record and returns a string illustration of the record. The string illustration of the record begins with the worth of the present Node, specified by its information/$information/Knowledge property, adopted by a whitespace character, an arrow, and one other whitespace character (" -> "), adopted by the remainder of the record. The top of the string illustration of a listing should at all times finish with None. For instance, given the next record:

Node(1, Node(2, Node(3)))

… its string illustration can be:

"1 -> 2 -> 3 -> None"

And given the next linked record:

Node(0, Node(1, Node(4, Node(9, Node(16)))))

… its string illustration can be:

"0 -> 1 -> 4 -> 9 -> 16 -> None"

Be aware that None itself can be thought of a sound linked record. In that case, its string illustration would merely be "None" (once more, relying on the language).

The answer in Python code

Choice 1:

Node.__str__ = lambda self: "%s -> %s" % (self.information, self.subsequent)
stringify = str

Choice 2:

def stringify(ll):
    r = []
    whereas ll:
        r, ll = r + [str(ll.data)], ll.subsequent
    return ' -> '.be a part of(r + ['None'])

Choice 3:

class Node():
    def __init__(self, information, subsequent = None):
        self.information = information
        self.subsequent = subsequent


def stringify(node):
    ok = ''
    whereas True:
        if node == None:
            ok += 'None'
            return ok
        else:
            ok += '{} -> '.format(node.information)
            node = node.subsequent

Check instances to validate our answer

take a look at.describe("stringify()")

take a look at.it("ought to cross the instance assessments as proven within the Description")
take a look at.assert_equals(stringify(Node(0, Node(1, Node(2, Node(3))))), '0 -> 1 -> 2 -> 3 -> None')
take a look at.assert_equals(stringify(None), 'None')
take a look at.assert_equals(stringify(Node(0, Node(1, Node(4, Node(9, Node(16)))))), '0 -> 1 -> 4 -> 9 -> 16 -> None')

[ad_2]

Leave a Reply