数组和列表(Python)

诈胡艺术 2020-11-13 03:19:57
Python CSDN 数组 列表


目录

【动态数组】

编程实现

相关类型题:

【合并两个有序数组】

【缺失的第一个正数】

【链表】(单列表)

编程实现

相关类型题:

【环形列表】

【合并两个有序链表】


【动态数组】

  • 编程实现

实现,以及增删改查操作:

#参考:https://www.cnblogs.com/kumata/p/9098137.html
import ctypes
class DynamicArray:
def __init__(self):#特殊方法
self._n = 0
self._capacity = 10
self._A = self._make_array(self._capacity)
def __len__ (self):
return self._n
def is_empty(self):
return self._n==0
# O(1)
def __getitem__ (self, k):
if k<0 or k>=self._n:
raise Exception("out of index")
return self._A[k]
# O(1)
def append(self, obj):
if self._n == self._capacity:
self._resize(2*self._capacity)
self._A[self._n] = obj
self._n += 1
def _make_array(self, c):
return (c* ctypes.py_object)()
def _resize(self, c):
B = self._make_array(c)
for i in range(self._n):
B[i] = self._A[i]
self._A = B
self._capacity = c
# O(n)
def insert(self, k, value):
if k<0 or k>=self._n:
raise Exception("out index")
if self._n == self._capacity:
self._resize(2*self._capacity)
for i in range(self._n,k,-1):
self._A[i] = self._A[i-1]
self._A[k] = value
self._n +=1
# O(n)
def remove(self, value):
for k in range(self._n):
if self._A[k] == value:
for i in range(k,self._n-1):
self._A[i] = self._A[i+1]
self._A[self._n-1] = None
self._n -= 1
return
def _print(self):
for i in range(self._n):
print self._A[i],' ',
print ''

测试程序:

mylist = DynamicArray()
print ('size was: ', str(len(mylist)))
mylist.append(10)
mylist.append(20)
mylist.append(30)
mylist._print()
mylist.insert(0, 0)
mylist.insert(1, 5)
mylist.insert(3, 15)
mylist._print()
mylist.remove(20)
mylist._print()
print ('size is: ', str(len(mylist)))

测试结果输出:

('size was: ', '0')
10 20 30
0 5 10 15 20 30
0 5 10 15 30
('size is: ', '5')
  • 相关类型题:

【合并两个有序数组】

给定两个有序整数数组 nums1 和 nums2,将 nums2 合并到 nums1 使得 num1 成为一个有序数组。

class Solution(object):
def merge(self, nums1, m, nums2, n):
"""
:type nums1: List[int]
:type m: int
:type nums2: List[int]
:type n: int
:rtype: void Do not return anything, modify nums1 in-place instead.
"""
index = m+n-1
i = m-1
j = n-1
while index>=0:#从末尾开始
if i<0:
nums1[index] = nums2[j]
j -= 1
elif j<0:
nums1[index] = nums1[i]
i -= 1
else:
if nums1[i]>nums2[j]:
nums1[index] = nums1[i]
i -= 1
else:
nums1[index] = nums2[j]
j -= 1
index -= 1

缺失的第一个正数

给定一个未排序的整数数组,找出其中没有出现的最小的正整数。

class Solution(object):
def firstMissingPositive(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
nums.sort()
min_num = 1
for i in nums:
if i == min_num:
min_num += 1
elif i>min_num:
return min_num
return min_num

【链表】(单列表)

  • 编程实现

实现,以及增删改查、反转、输出等操作。

节点类:

#先定一个node的类
class Node(): #value + next
def __init__ (self, value = None, next = None):
self._value = value
self._next = next
def getValue(self):
return self._value
def getNext(self):
return self._next
def setValue(self,new_value):
self._value = new_value
def setNext(self,new_next):
self._next = new_next

列表:

#实现Linked List及其各类操作方法
class LinkedList():
def __init__(self): #初始化链表为空表
self._head = Node()
self._tail = None
self._length = 0
#检测是否为空
def isEmpty(self):
return self._length == 0
#add在链表前端添加元素:O(1)
def add(self,value):
self._head.setValue(value)
new_node = Node(value,self._head)
self._head = Node(next=new_node)
self._length += 1
#append在链表尾部添加元素:O(n)
def append(self,value):
new_node = Node(value,None)
if self._tail == None:
self._tail = new_node
self._head.setNext(new_node)
else:
self._tail.setNext(new_node)
self._tail = new_node
self._length += 1
#search检索元素是否在链表中
def search(self,value):
current = self._head.getNext()
found_value = False
while current != None:
if current.getValue() == value:
found_value = True
break
else:
current = current.getNext()
return found_value
#index索引元素在链表中的位置
def index(self,value):
current = self._head.getNext()
count =0
found =False
while current !=None:
count +=1
if current.getValue() == value:
found = True
break
current = current.getNext()
if found:
return count
else:
raise Exception("no found")
#remove删除链表中的某项元素
def remove(self,value):
current = self._head
found =False
# if current.getValue() == value:
# self._head = current.getNext()
# self._length -= 1
# return
while current.getNext() !=None:
if current.getNext().getValue() == value:
found = True
current.setNext(current.getNext().getNext())
self._length -= 1
return
current = current.getNext()
if found:
return
else:
raise Exception("no found")
#insert链表中插入元素
def insert(self,pos,value):
if pos>self._length:
raise Exception("out index")
else:
current = self._head
pre = None
for i in range(1,self._length):
pre = current
current = current.getNext()
if pos == i:
new_node = Node(value)
new_node.setNext(current)
pre.setNext(new_node)
self._length += 1
break
#列表反转
def reverse(self):
if self._length == 1:
return
pre = self._head.getNext()
self._tail = Node(value=pre.getValue())
current = pre.getNext()
pre.setNext(None)
while current != None:
next_node = current.getNext()
current.setNext(pre)
pre = current
current = next_node
# next_node = next_node.getNext()
self._head = Node(next=pre)
#输出
def _print(self):
if self._length == 0:
return
current = self._head.getNext()
# print current.getValue()
while current != None:
print '->',current.getValue(),
current = current.getNext()
print ''

测试程序:

mylist = LinkedList()
mylist.append(10)
mylist.append(20)
mylist.append(30)
mylist._print()
mylist.insert(1, 5)
mylist.insert(3, 15)
mylist._print()
mylist.remove(20)
mylist._print()

测试结果输出:

-> 10 -> 20 -> 30
-> 5 -> 10 -> 15 -> 20 -> 30
-> 5 -> 10 -> 15 -> 30 
  • 相关类型题:

【环形列表】

给定一个链表,判断链表中是否有环。

#双指针
class Solution(object):
def hasCycle(self, head):
"""
:type head: ListNode
:rtype: bool
"""
if head==None or head.next==None:
return False
slow = head
fast = head.next
while slow != fast:
if fast==None or fast.next==None:
return False
slow = slow.next
fast = fast.next.next
return True

合并两个有序链表

将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。 

class Solution(object):
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
if not l1:
return l2
if not l2:
return l1
head = ListNode(0)
now = head
while l1 and l2:
if l1.val <= l2.val:
now.next = ListNode(l1.val)
l1 = l1.next
now = now.next
else:
now.next = ListNode(l2.val)
l2 = l2.next
now = now.next
if l1:
now.next = l1
return head.next
if l2:
now.next = l2
return head.next

 

版权声明
本文为[诈胡艺术]所创,转载请带上原文链接,感谢
https://blog.csdn.net/m0_38019841/article/details/88032797

  1. 利用Python爬虫获取招聘网站职位信息
  2. Using Python crawler to obtain job information of recruitment website
  3. Several highly rated Python libraries arrow, jsonpath, psutil and tenacity are recommended
  4. Python装饰器
  5. Python实现LDAP认证
  6. Python decorator
  7. Implementing LDAP authentication with Python
  8. Vscode configures Python development environment!
  9. In Python, how dare you say you can't log module? ️
  10. 我收藏的有关Python的电子书和资料
  11. python 中 lambda的一些tips
  12. python中字典的一些tips
  13. python 用生成器生成斐波那契数列
  14. python脚本转pyc踩了个坑。。。
  15. My collection of e-books and materials about Python
  16. Some tips of lambda in Python
  17. Some tips of dictionary in Python
  18. Using Python generator to generate Fibonacci sequence
  19. The conversion of Python script to PyC stepped on a pit...
  20. Python游戏开发,pygame模块,Python实现扫雷小游戏
  21. Python game development, pyGame module, python implementation of minesweeping games
  22. Python实用工具,email模块,Python实现邮件远程控制自己电脑
  23. Python utility, email module, python realizes mail remote control of its own computer
  24. 毫无头绪的自学Python,你可能连门槛都摸不到!【最佳学习路线】
  25. Python读取二进制文件代码方法解析
  26. Python字典的实现原理
  27. Without a clue, you may not even touch the threshold【 Best learning route]
  28. Parsing method of Python reading binary file code
  29. Implementation principle of Python dictionary
  30. You must know the function of pandas to parse JSON data - JSON_ normalize()
  31. Python实用案例,私人定制,Python自动化生成爱豆专属2021日历
  32. Python practical case, private customization, python automatic generation of Adu exclusive 2021 calendar
  33. 《Python实例》震惊了,用Python这么简单实现了聊天系统的脏话,广告检测
  34. "Python instance" was shocked and realized the dirty words and advertisement detection of the chat system in Python
  35. Convolutional neural network processing sequence for Python deep learning
  36. Python data structure and algorithm (1) -- enum type enum
  37. 超全大厂算法岗百问百答(推荐系统/机器学习/深度学习/C++/Spark/python)
  38. 【Python进阶】你真的明白NumPy中的ndarray吗?
  39. All questions and answers for algorithm posts of super large factories (recommended system / machine learning / deep learning / C + + / spark / Python)
  40. [advanced Python] do you really understand ndarray in numpy?
  41. 【Python进阶】Python进阶专栏栏主自述:不忘初心,砥砺前行
  42. [advanced Python] Python advanced column main readme: never forget the original intention and forge ahead
  43. python垃圾回收和缓存管理
  44. java调用Python程序
  45. java调用Python程序
  46. Python常用函数有哪些?Python基础入门课程
  47. Python garbage collection and cache management
  48. Java calling Python program
  49. Java calling Python program
  50. What functions are commonly used in Python? Introduction to Python Basics
  51. Python basic knowledge
  52. Anaconda5.2 安装 Python 库(MySQLdb)的方法
  53. Python实现对脑电数据情绪分析
  54. Anaconda 5.2 method of installing Python Library (mysqldb)
  55. Python implements emotion analysis of EEG data
  56. Master some advanced usage of Python in 30 seconds, which makes others envy it
  57. python爬取百度图片并对图片做一系列处理
  58. Python crawls Baidu pictures and does a series of processing on them
  59. python链接mysql数据库
  60. Python link MySQL database