How to use Javascript JSON.stringify similar method in Python All In One
如何在 Python 中使用类似 JavaScript JSON.stringify 的方法
应用场景
比较两个数组(列表)对象是否相等 / compares two array (list) objects for equality
// js
arr1 = [1,2,3]
arr2 = [1,2,3]
JSON.stringify(arr1) === JSON.stringify(arr2)
# python
import json
list1 = [1,2,3]
list2 = [1,2,3]
json.dumps(list1) == json.dumps(list2)
demos
比较两个
列表
是否相等
import json
list1 = [1,2,3]
list2 = [1,2,3]
result = json.dumps(list1) == json.dumps(list2)
print("result =", result)
"""
$ py3 ./json.stringify_json.dumps.py
result = True
"""
比较两个
链表
是否相等
# Definition for singly-linked list.
from typing import Optional
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def middleNode(self, head: Optional[ListNode]) -> Optional[ListNode]:
# DFS / BFS
def getLength(node):
temp = node
length = 1;
while temp.next != None:
length += 1
temp = temp.next
return length
def dfs(node, length):
temp = node
# 向下取整除法
l = length // 2
while l > 0:
l -= 1
temp = temp.next
return temp
return dfs(head, getLength(head))
def SingleLinkedListGenerator(num: int, start: int = 1) -> Optional[ListNode]:
head = ListNode()
temp = head
for i in range(num):
if(start == 1):
temp.next = ListNode(i + start)
# print("temp.next.val =", temp.next.val)
temp = temp.next
else:
if(i < start):
temp.next = ListNode(i + start)
# print("temp.next.val =", temp.next.val)
temp = temp.next
return head.next
# 比较两个链表是否相等
def compareListEqual(one, two):
while one and two and one.val == two.val:
one = one.next
two = two.next
# 同时为 None ✅
if not one and not two:
return True
return False
input = SingleLinkedListGenerator(7)
# print("\n")
result = SingleLinkedListGenerator(7, 4)
# i = [1,2,3,4,5,6,7]
# r = [4,5,6,7]
solution = Solution()
case = solution.middleNode(input)
test = compareListEqual(case, result)
if test:
print("✅ test =", test)
else:
print("❌ test =", test)
# how to compare two linked lists are equal in Python ??? JSON.stringify(list)
# https://www.cnblogs.com/xgqfrms/p/17626511.html
# # test cases
# t1 = 14
# t2 = 8
# t3 = 123
# tests = [t1, t2, t3]
# r1 = 6
# r2= 4
# r3 = 12
# results = [r1, r2, r3]
# def test():
# solution = Solution()
# for index, test in enumerate(tests):
# value = solution.numberOfSteps(test)
# result = results[index]
# if(str(value) == str(result)):
# print("✅ passed", index)
# else:
# print("❌ failed", value, result)
# test()
"""
$ py3 ./876_middle-of-the-linked-list.py
https://leetcode.com/problems/middle-of-the-linked-list/
https://www.cnblogs.com/xgqfrms/p/17624242.html
"""
https://www.cnblogs.com/xgqfrms/p/17624242.html