Python学习笔记(九)——链表、背包与多项式

一、Linked List

1.The singly linked list 

class ListNode:
    def __init__(self, data):
        self.data = data
        self.next = None

#遍历链表
def traversal(head):
    curNode = head
    while curNode is not None:
        print(curNode.data)
        curNode = curNode.next

#搜索未排序的链表
def unorderedSearch(head, target):
    curNode = head
    while curNode is not None and curNode.data != target:
        curNode = curNode.next
    return curNode is not None

#移除链表中的结点
def remove(head,target):
    preNode = None
    curNode = head
    while curNode is not None and curNode.data != target:
        preNode = curNode
        curNode = curNode.next
    if curNode is not None:
        if curNode is head:
            head = curNode.next
        else:
            preNode.next = curNode.next
    return head

#在前面增加结点
def prepend(head, item):
    newNode = ListNode(item)
    newNode.next = head
    head = newNode
    return head

#在链表后面增加结点
def append(head, tail, item):
    newNode = ListNode(item)
    if head is None:
        head = newNode
    else:
        tail.next = newNode
    tail = newNode
    return head

#利用head和tail移除结点
def remove_tail(head, tail, target):
    predNode = None
    curNode = head
    while curNode is not None and curNode.data != target:
        predNode = curNode
        curNode = curNode.next
    
    if curNode is not None:
        if curNode is head:
            head = curNode.next
        else:
            predNode.next = curNode.next
        if curNode is tail:
            tail = predNode
    return head

#在排好序的链表中搜索数据
def sortedSearch(head, target):
    curNode = head
    while curNode is not None and curNode.data <= target :
        if curNode.data == target:
            return True
        else:
            curNode = curNode.next
    return False

#在已排好序的链表中插入数据(先把数据转化为结点)
def insert(head, value):
    predNode = None
    curNode = head
    while curNode is not None and value > curNode.data:
        predNode = curNode
        curNode = curNode.next
    newNode = ListNode(value)
    newNode.next = curNode

    if curNode is head:
        head = newNode
    else:
        predNode.next = newNode

    return head

def main():
    a = ListNode(12)
    b = ListNode(13)
    a.next = b

    head = a
    head = prepend(head, 10)
    print(head.data)
    print(head.next.data)
    print(head.next.next.data)
    #由此可见,用函数可以改变链表。不会出现无法改变实参的情况。
    #这里声明一下,用python编写关于改变联表的函数返回值均为head,即链表的起点。

    tail = b
    head = append(head, tail, 36)
    head = insert(head, 32)
    print(head.data)
    print(head.next.data)
    print(head.next.next.data)
    print(head.next.next.next.data)
    print(head.next.next.next.next.data)
    print(sortedSearch(head, 12))

main()

'''
输出如下:
10
12
13
10
12
13
32
36
True

再次强调,用函数可以改变链表。不会出现无法改变实参的情况。
这里规定用python编写关于改变联表的函数返回值均为head,即链表的起点。
'''

2.双链表

class DListNode:
    def __init__(self, data):
        self.data = data
        self.next = None
        self.prev = None
    
def revTraversal(tail):
    curNode = tail
    while curNode is not None:
        print(curNode.data)
        curNode = curNode.prev

def probe(head, probe, target):
    if head is None:
        return False
    elif probe is None:
        probe = head
    
    if target < probe.data:
        while probe is not None and target <= probe.data:
            if target == probe.data:
                return True
            else:
                probe = probe.prev
    else:
        while probe is not None and target >= probe.data:
            if target == probe.data:
                return True
            else:
                probe = probe.next
    return False
        
def insert(head, tail, value):
    newNode = DListNode(value)
    if head is None:
        head = newNode
        tail = head
    elif value < head.data:
        newNode.next = head
        head = newNode
    elif value > tail.data:
        newNode.prev = tail
        tail.next = newNode
        tail = newNode
    else:
        node = head
        while node is not None and node.data < value :
            node = node.next
        
        newNode.next = node
        newNode.prev = node.prev
        node.prev.next = newNode
        node.prev = newNode

3.循环链表

class ListNode:
    def __init__(self, data):
        self.data = data
        self.next = None

# Traversing a circular linked list.
def traversal(listRef):
    curNode = listRef
    done = listRef is None
    while not done:
        curNode = curNode.next
        print(curNode.data)
        done = curNode is listRef

def searchCircularList(listRef, target):
    curNode = listRef
    done = listRef is None
    while not done:   # When 'done' is True, it terminates. 
        curNode = curNode.next
        if curNode.data == target:
            return True
        else:
            done = curNode is listRef or curNode.data > target
    return False


# Inserting a node into an ordered circular linked list.
# 默认 listRef 是最大的数据。
def insert(value, listRef, target):
    newNode = ListNode(value)
    if listRef is None:                   # empty list
        listRef = newNode
        newNode.next = newNode
    elif value < listRef.next.data:       # insert in front
        newNode.next = listRef.next
        listRef.next = newNode
    elif value >  listRef.data:           # insert in back
        newNode.next = listRef.next
        listRef.next = newNode
        listRef = newNode
    else:                                 # insert in the middle
        predNode = None
        curNode = listRef
        done = listRef is None
        while not done:
            predNode = curNode
            predNode = curNode.next
            done = curNode is listRef or curNode.data > target
        newNode.next = curNode
        predNode.next = newNode
        

 

二、Bags

1.不用链表

class Bag :
    def __init__(self):
        self._theItems = list()
    
    #Returns the number of items in the bag.
    def __len__(self):
        return len(self._theItems)
    
    # Determines if an item is contained in the bag. 
    def __contains__(self, item):
        return item in self._theItems
    
    #Adds a new item to the bag.
    def add(self, item):
        self._theItems.append(item)
    
    # Removes and returns an instance of the item from the bag.
    def remove(self, item):
        assert item in self._theItems, "The item must be in the bag."
        ndx = self._theItems.index(item)
        return self._theItems.pop(ndx)
    
    def __iter__(self):
        return _BagIterator(self._theItems)

class _BagIterator:
    def __init__(self, theList):
        self._bagItems = theList
        self._curItem = 0
    def __iter__(self):
        return self
    
    def __next__(self):
        if self._curItem < len(self._bagItems):
            item = self._bagItems[self._curItem]
            self._curItem += 1
        else:
            raise StopIteration

 

2.使用链表

class Bag:
    # Constructs an empty bag.
    def __init__(self):
        self._head = None
        self._size = 0
    def __len__(self):
        return self._size
    
    def __contains__(self, target):
        curNode = self._head
        while curNode is not None and curNode.item != target:
            curNode = curNode.next
        return curNode is not None
    
    #Adds a new item to the bag.
    def add(self, item):
        newNode = _BagListNode(item)
        newNode.next = self._head
        self._head = newNode
        self._size += 1
    
    def remove(self, item):
        predNode = None
        curNode = self._head
        while curNode is not None and curNode.item != item :
            predNode = curNode
            curNode = curNode.next
        
        assert curNode is not None, "The item must be in the bag."
        
        #Unlink the node and return the item.
        self._size -= 1
        if curNode is self._head:
            self._head = curNode.next
        else:
            predNode.next = curNode.next
        return curNode.item

    def __iter__(self):
        return _BagIterator(self._head)
    
class _BagListNode(object):
    def __init__(self, item):
        self.item = item
        self.next = None

class _BagIterator():
    def __init__(self, listHead):
        self._curNode = listHead
    
    def __iter__(self):
        return self
    def __next__(self):
        if self._curNode is None:
            raise StopIteration
        else:
            item = self._curNode.item
            self._curNode = self._curNode.next
            return item
            
bag = Bag()
bag.add('a')
bag.add('b')
bag.add(3)
bag.add(8)
bag.add(10)
bag.remove(8)
print(bag.__len__())
print(len(bag))
for item in bag:
    print(item, end = ' ')


'''
输出:
5
5
10 8 3 b a
'''

 

三、Polynomial

class Polynomial:
    def __init__(self, degree = None, coefficient = None):
        if degree is None:
            self._polyHead = None
        else:
            self._polyHead = _PolyTermNode(degree, coefficient)
        self._polyTail = self._polyHead

    # Return the degree of the polynomial. 
    def degree(self):
        if self._polyHead is None:
            return -1
        else:
            return self._polyHead.degree  #注意,degree后面没有括号,说明不是方法。

    # Return the coefficient for the term of the given degree.
    def __getitem__(self, degree):
        assert self.degree() >= 0,\
        "Operation not permitted on an empty polynomial." 
        curNode = self._polyHead
        while curNode is not None and curNode.degree > degree:
            curNode = curNode.next
        
        if curNode is None or curNode.degree != degree:
            return 0.0
        else:
            return curNode.coefficient

    # Evaluate the polynomial at the given scalar value.
    def evaluate(self, scalar):
        assert self.degree() >= 0,\
        "Only non-empty polynomials can be evaluated."
        result = 0.0
        curNode = self._polyHead
        while curNode is not None:
            result += curNode.coefficient * (scalar ** curNode.degree)
            curNode = curNode.next
        return result
    
    def simple_add(self, rhsPoly):
        newPoly = Polynomial()
        if self.degree() > rhsPoly.degree():
            maxDegree = self.degree()
        else:
            maxDegree = rhsPoly.degree()
        
        i = maxDegree
        while i >= 0:
            value = self[i] + rhsPoly[i]  #用中括号取系数值是__getitem__的效果。
            # print(value)
            newPoly._appendTem(i, value)
            i -= 1

        return newPoly
    
    def __add__(self, rhsPoly):
        assert self.degree() >= 0 and rhsPoly.degree() >= 0,\
        "Addition only allowed on non-empty polynomials."
        newPoly = Polynomial()
        nodeA = self._polyHead
        nodeB = rhsPoly._polyHead

        while nodeA is not None and nodeB is not None:
            if nodeA.degree > nodeB.degree:
                degree = nodeA.degree
                value = nodeA.coefficient
                nodeA = nodeA.next
            elif nodeA.degree < nodeB.degree:
                degree = nodeB.degree
                value = nodeB.coefficient
                nodeB = nodeB.next
            else:
                degree = nodeA.degree
                value = nodeA.coefficient + nodeB.coefficient
                nodeA = nodeA.next
                nodeB = nodeB.next
            newPoly._appendTem(degree, value)
        while nodeA is not None:
            newPoly._appendTem(nodeA.degree, nodeA.coefficient)
            nodeA = nodeA.next
        while nodeB is not None:
            newPoly._appendTem(nodeB.degree, nodeB.coefficient)
            nodeB = nodeB.next
        
        return newPoly
        

    
    def multiply(self, rhsPoly):
        assert self.degree() >= 0 and rhsPoly.degree() >= 0,\
        "Multiplication only allowed on non-empty polynomials." 
        
        # Create a new polynomial by multiplying rhsPoly by the first term. 
        node = self._polyHead
        newPoly = rhsPoly._termMultiply(node)

        node = node.next
        while node is not None:
            tempPoly = rhsPoly._termMultiply(node)
            newPoly = newPoly.add(tempPoly)
            node = node.next
        return newPoly

    # Helper method for creating a new polynomial from 
    # multiplying an existing polynomial by another term. 
    def _termMultiply(self, termNode):
        newPoly = Polynomial()

        # Iterate through the terms and compute the 
        # product of each term and the term in termNode. 
        curr = self._polyHead
        while curr is not None:
            # Compute the product of the term.
            newDegree = curr.degree + termNode.degree
            newCoeff = curr.coefficient * termNode.coefficient
            newPoly._appendTem(newDegree, newCoeff)
            curr = curr.next
        return newPoly


    # Helper method for appending terms to the polynomial.
    def _appendTem(self, degree, coefficient):
        if coefficient != 0.0:
            newTerm = _PolyTermNode(degree, coefficient)
            if self._polyHead is None:
                self._polyHead = newTerm
            else:
                self._polyTail = newTerm
    
    
class _PolyTermNode(object):
    def __init__(self, degree, coefficient):
        self.degree = degree
        self.coefficient = coefficient
        self.next = None


p1 = Polynomial(2,2)
p2 = Polynomial(2,1)
new = p1.simple_add(p2)
print(new.evaluate(2))
new2 = p1 + p2
print(new2.evaluate(2))
new3 = p1.multiply(p2)
print(new3.evaluate(2))



'''
output:
12.0
12.0
32.0
'''

四、Text Editor

未解决(但书上有完整过程)

 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是Python实现的链表多项式多项式的示例代码: ```python class Node: def __init__(self, coeff, exp, next=None): self.coeff = coeff self.exp = exp self.next = next class Polynomial: def __init__(self, head=None): self.head = head def insert(self, coeff, exp): if self.head is None: self.head = Node(coeff, exp) else: curr = self.head while curr.next is not None: curr = curr.next curr.next = Node(coeff, exp) def add(self, poly2): result = Polynomial() curr1 = self.head curr2 = poly2.head while curr1 is not None and curr2 is not None: if curr1.exp > curr2.exp: result.insert(curr1.coeff, curr1.exp) curr1 = curr1.next elif curr1.exp < curr2.exp: result.insert(curr2.coeff, curr2.exp) curr2 = curr2.next else: result.insert(curr1.coeff + curr2.coeff, curr1.exp) curr1 = curr1.next curr2 = curr2.next while curr1 is not None: result.insert(curr1.coeff, curr1.exp) curr1 = curr1.next while curr2 is not None: result.insert(curr2.coeff, curr2.exp) curr2 = curr2.next return result def display(self): curr = self.head while curr is not None: print(curr.coeff, "x^", curr.exp, end=" ") curr = curr.next print() # 示例 p1 = Polynomial() p1.insert(1, 2) p1.insert(2, 1) p1.insert(3, 0) p2 = Polynomial() p2.insert(2, 1) p2.insert(1, 0) p3 = p1.add(p2) p1.display() # 输出 "1 x^ 2 2 x^ 1 3 x^ 0" p2.display() # 输出 "2 x^ 1 1 x^ 0" p3.display() # 输出 "1 x^ 2 4 x^ 1 4 x^ 0" ``` 以上代码中,`Node`类表示链表节点,包含系数和指数两个属性,以及指向下一个节点的指针。`Polynomial`类表示多项式,包含一个链表作为成员变量,支持插入节点、多项式加法和显示多项式等操作。在多项式加法中,使用两个指针分别指向两个多项式的头节点,遍历链表将相同指数的项相加,并将结果插入到结果多项式中。最后,将剩余的项依次插入到结果多项式中。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值