python与算法:单链表剖分函数(对链表的元素可以按照是否满足特定功能切分为两个新的链表)

简介: python与算法:单链表剖分函数(对链表的元素可以按照是否满足特定功能切分为两个新的链表)
def funct(x):
    if x%2==0:
        return True
    else:
        return False
def partition(lst,pred):
    satisfy_list=LList()
    unsatisfy_list=LList()
    p=lst._head
    # lst里面有元素
    while p.next is not None:
        elem=p.elem
        # 如果满足条件,加入到
        if pred(elem):
            if satisfy_list._head is None:
                satisfy_list._head=LNode(elem)
            q=satisfy_list._head
            while q.next is not None:
                q=q.next
            q.next=LNode(elem)
        else:
            if unsatisfy_list._head is None:
                unsatisfy_list._head=LNode(elem)
            r=unsatisfy_list._head
            while r.next is not None:
                r=r.next
            r.next=LNode(elem)
        p=p.next
    satisfy_list.printall()
    unsatisfy_list.printall()
    return satisfy_list,unsatisfy_list
# 测试,程序需要继承前文的LList类
# 创造一个链表加入元素
m1=LList()
for i in range(20):
    m1.append(i)
m2=LList()
for i in range(11,20):
    m2.append(i)
print('m1',m1.printall())
print('m2',m2.printall())
x,y=partition(m2,funct)
print(m2.printall())
print(x.printall())
print(y.printall())

从算法的效率上来看,实现这个功能用顺序表或者双向链表效率会更高,比单链表会高很多,目前的单链表时间开销应该是O(n^2),使用python的list可以实现O(n),或者用向量,时间开销成本更低。

目录
相关文章
|
11天前
|
数据挖掘 数据处理 索引
python常用pandas函数nlargest / nsmallest及其手动实现
python常用pandas函数nlargest / nsmallest及其手动实现
26 0
|
2天前
|
NoSQL Serverless Python
在Python的Pandas中,可以通过直接赋值或使用apply函数在DataFrame添加新列。
在Python的Pandas中,可以通过直接赋值或使用apply函数在DataFrame添加新列。方法一是直接赋值,如`df['C'] = 0`,创建新列C并初始化为0。方法二是应用函数,例如定义`add_column`函数计算A列和B列之和,然后使用`df.apply(add_column, axis=1)`,使C列存储每行A、B列的和。
13 0
|
4天前
|
机器学习/深度学习 数据可视化 TensorFlow
Python用线性回归和TensorFlow非线性概率神经网络不同激活函数分析可视化
Python用线性回归和TensorFlow非线性概率神经网络不同激活函数分析可视化
|
6天前
|
Python 容器
python内置函数、数学模块、随机模块(二)
python内置函数、数学模块、随机模块(二)
|
6天前
|
索引 Python
python内置函数、数学模块、随机模块(一)
python内置函数、数学模块、随机模块(一)
|
6天前
|
Python
深入理解python的闭包函数
深入理解python的闭包函数
|
6天前
|
Python
python函数的返回值、嵌套方式以及函数中的变量(二)
python函数的返回值、嵌套方式以及函数中的变量(二)
|
6天前
|
存储 Python 容器
python函数的返回值、嵌套方式以及函数中的变量(一)
python函数的返回值、嵌套方式以及函数中的变量(一)
|
6天前
|
Python
深度解读python的函数(二):
深度解读python的函数(二)
|
6天前
|
Python
深度解读python的函数(一)
深度解读python的函数(一)