函数、排序、线性数据结构

来源:互联网 发布:金庸武侠知乎 编辑:程序博客网 时间:2024/06/04 19:17

大学计算机–Python算法实践

李金双、李凤云、张昱

函数定义

# def 函数名([形参列表]):#   函数体def add(a, b):return a + bc = add(7.6, 3.9)print(c)    #11.5

排序

a = [6, 9, 23, 15, 1, 5, 34]b = sorted(a)  #sorted()函数a.sort()  #list提供的sort()方法,改变了aprint(a)  #[1, 5, 6, 9, 15, 23, 34]print(b)  #[1, 5, 6, 9, 15, 23, 34]b = sorted(a, reverse = True)a.sort(reverse = True)print(a)  #[34, 23, 15, 9, 6, 5, 1]print(b)  #[34, 23, 15, 9, 6, 5, 1]

交换两个数的值

a = 2b = 9a, b = b, a  #exchangeprint(a, b)  #9 2

线性数据结构

  • 通常直接用列表作为数组

  • 栈也可通过列表实现

    • append()对应入栈操作

    • pop()对应出栈操作

    • s = []s.append(2)s.append(3)print(s)  #[2, 3]s.pop()print(s)  #[2]s.pop()print(s)  #[]
  • collections.deque是双向队列,支持任意端添加删除数据

    from collections import dequedq = deque()dq.append(1)  #尾部添加元素dq.append(2)print(dq)  #deque([1, 2])dq.appendleft(3)  #首部添加元素dq.appendleft(4)print(dq)  #deque([4, 3, 1, 2])print(dq.pop())  #弹出尾部元素 2print(dq.popleft())  #弹出首部元素 4print(dq)  #deque([3, 1])dq.reverse()  #反转print(dq)  #deque([1, 3])dq.clear()  #清空print(dq)  #deque([])

  • 树是节点和边的集合

  • 属非线性结构

  • 对于二叉树,设 i 度节点的数目为 Ni

    • N0+N1+N2=N
    • N00+N11+N22=N1
  • 三种遍历方式:先序、中序、后序

原创粉丝点击