首页 > 编程语言 >How to compare two linked lists are equal in Python All In One

How to compare two linked lists are equal in Python All In One

时间:2023-08-13 14:23:29浏览次数:45  
标签:compare ListNode temp Python head equal return next def

How to compare two linked lists are equal in Python All In One

在 Python 中如何比较两个链表是否相等

# 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) -> Optional[ListNode]:
  head = ListNode()
  temp = head
  for i in range(num):
    temp.next = ListNode(i + 1)
    temp = temp.next
  return head.next

i = SingleLinkedListGenerator(7)
r = [4,5,6,7]

print("input ", i)

# how to compare two linked lists are equal in Python ??? JSON.stringify(list)


"""
$ py3 ./876_middle-of-the-linked-list.py

"""

https://leetcode.com/problems/middle-of-the-linked-list/

# # 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()


solutions

def equal(self, other):
    while self and other and self.value == other.value:
        self = self.next
        other = other.next
    if not self and not other:
        return True
    return False

def check_equality(list_1, list_2):
   curr_1 = list_1.head
   curr_2 = list_2.head
   while (curr_1 and curr_2):
      if curr_1.data != curr_2.data:
         return False
      curr_1 = curr_1.next
      curr_2 = curr_2.next
   if curr_1 is None and curr_2 is None:
      return True
   else:
      return False

json

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

"""

https://www.cnblogs.com/xgqfrms/p/17626511.html

demos

image

# 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) -> Optional[ListNode]:
#   head = ListNode()
#   temp = head
#   for i in range(num):
#     temp.next = ListNode(i + 1)
#     temp = temp.next
#   return head.next

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)


(

标签:compare,ListNode,temp,Python,head,equal,return,next,def
From: https://www.cnblogs.com/xgqfrms/p/17624242.html

相关文章

  • How to use Javascript JSON.stringify similar method in Python All In One
    HowtouseJavascriptJSON.stringifysimilarmethodinPythonAllInOne如何在Python中使用类似JavaScriptJSON.stringify的方法应用场景比较两个数组(列表)对象是否相等/comparestwoarray(list)objectsforequality//jsarr1=[1,2,3]arr2=[1,2,3]......
  • Python - 会考必过篇
    文章简介该文章是为了帮助身边朋友为了会考信息与技术将Python这门语言给学会而创作的。开发工具在线运行环境腾讯Python实验室:Python|Coding1024Code:Python|1024CodeLwebapp:Python|Lwebapp!>以上在线运行环境,前两种需要登录,目前找到的仅有第三种比较好用,......
  • Python 农历公历相互转换
    Python农历公历相互转换stackOverflowsh关注IP属地:江苏0.2252019.02.1918:23:48字数2,054阅读6,862背景日常用python处理各种数据分析工作,最近需要对历年春节期间的数据做一些对比工作,本来只是用了一个简单的日期数组来进行,但后来发现一些数据在农历日期进行对比......
  • Python代码分享-获取B站粉丝数量
    分享一下一段Python代码。#获取B站粉丝数量#冰河之刃#2020-08-02importrequestsimportjsonurl="https://api.bilibili.com/x/relation/stat?vmid=490458635"payload={}#发起请求response=requests.request("GET",url,data=payload)#print(response.......
  • 学习笔记-流畅的Python 1st
    P31和*都遵循不修改原有的操作对象,而是创建一个新的序列>>>a=[1,2,3]>>>c=a*2>>>a[0]=3>>>c[1,2,3,1,2,3]如果在a*n这个语句中,序列a里的元素是对其他可变对象的引用的话,你就需要格外注意了,因为这个式子的结果可能会出乎意料。比如,你想用my......
  • 4.0 Python 变量与作用域
    在python中,变量的作用域决定了变量在哪些位置可以被访问。一个程序中的变量并不是所有的地方都可以访问的,其访问权限决定于变量的赋值位置。python中有两种最基本的变量作用域:局部作用域和全局作用域。局部变量是在函数内部定义的变量,只能在其被声明的函数内部访问。而全局变量则......
  • 5.0 Python 定义并使用函数
    函数是python程序中的基本模块化单位,它是一段可重用的代码,可以被多次调用执行。函数接受一些输入参数,并且在执行时可能会产生一些输出结果。函数定义了一个功能的封装,使得代码能够模块化和组织结构化,更容易理解和维护。在python中,函数可以返回一个值或者不返回任何值,而且函数的参......
  • n、Appium_Python_Api
    一、Appium_Python_Api方法参考博客:https://blog.csdn.net/ezreal_tao/article/details/80911950https://cloud.tencent.com/developer/article/1569596contextscontexts(self):Returnsthecontextswithinthecurrentsession.返回当前会话中的上下文,使用后可以识别H5......
  • python简介
    python简介1.python的产生与应用python于1989年圣诞节期间由吉多·范罗苏姆(GuidovanRossum)(中文名字:龟叔)为打发时间开发的一个新脚本解释程序,作为ABC语言的一种继承。(龟叔:2005年加入谷歌至2012年,2013年加入Dropbox直到现在,依然掌握着Python发展的核心方向,被称为仁慈的独裁者)。......
  • python基础
    python基础一、python基础初识1.运行python代码。在d盘下创建一个t1.py文件内容是:print('helloworld')打开windows命令行输入cmd,确定后写入代码pythond:t1.py您已经运行了第一个python程序,即:终端---->cmd----->python文件路径。回车搞定~2.解释器。上一步中执......