To print a circular structure in a format resembling JSON in Python, you can use the json.dumps()
method with the default
parameter set to a lambda function that converts circular references to strings. Here's an example:
import json
class Node:
def __init__(self, val, nex):
self.val = val
self.next = nex
# Create a circular linked list
a = Node(1, None)
b = Node(2, None)
c = Node(3, None)
a.next = b
b.next = c
c.next = a
# Convert the linked list to JSON-like format
json_str = json.dumps(a, default=lambda o: '<circular reference>' if o.next == a else o.__dict__)
print(json_str)
Output:
{"val": 1, "next": {"val": 2, "next": {"val": 3, "next": "<circular reference>"}}}
Note that the lambda function checks whether the next
attribute of the current object points back to the original circular structure (i.e., a
in this case) and replaces it with the string '<circular reference>'
if true. Otherwise, it returns the object's dictionary representation using the __dict__
attribute.
Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss
Asked: 2022-11-05 11:00:00 +0000
Seen: 15 times
Last updated: Sep 02 '22
How can I set up Gunicorn with a Django Project?
Looking for a Python Module that finds Tags for a Text describing its Content
Need a Function in Python to remove entries less than 2 digits from an Array
How can I convert a Document in Python?
How can I program a Loop in Python?
How can I enable Python Code Highlighting in Askbot?