飞道的博客

Python基础知识的再整理

419人阅读  评论(0)

用Python在牛客刷题美滋滋,但基础知识不能只靠编译器提示,之前博客已经有对Python基础总结,趁机再把基础知识复习一遍吧,满足基本地算法刷题需要; 

目录

字符串及方法

list列表及方法

map函数及其他

 简单的几个算法题

面向对象、链表、二叉树

链表全部

链表简易版

二叉树


字符串及方法

包含字符串的常用操作:分割、替换、去空格、根据索引输出等


  
  1. # 字符串分割
  2. orgin_str= 'lsajgajga af jaslf jas alfjal sdsfarfa a jaslfja '
  3. list_str=orgin_str.split( ' ')
  4. #print(type(list_str))
  5. # replace 替换后返回新的字符串,而非在原始str上做替换;
  6. str_two=orgin_str.replace( 'af', 'yzg')
  7. #print(str_two,orgin_str)
  8. #print(str_two.find('yzg'))
  9. # join方法是str方法,把list和tuple都连接在一起,跟split反着来。
  10. str_three= 'b'
  11. #print(str_three.join(['d','r']))
  12. # 去空格
  13. xxx= ' flajfla sdsa '
  14. #print(xxx,xxx.lstrip(),xxx.lstrip())
  15. #print("原始数据是%s去掉空格后是%s" %xxx,%xxx)
  16. # 定位某个元素的第一个位置
  17. lista=[ 1, 2, 3, 4]
  18. #print(lista.index(1))
  19. sssstr = '12345'
  20. #print(sssstr[1:3])
  21. #print("下面输出一串数字:%s" %str)
  22. #print("原始数据是:%s,去掉空格后是:%s" %(xxx,xxx))
  23. # 字符串反转
  24. strsda= 'asdfghjkl'
  25. a=list(strsda)
  26. a.reverse()
  27. #print(''.join(a))

list列表及方法

包含list的反转、排序、遍历、删除、检索、str转换等;


  
  1. # sort()和reverse()把list排序和反转就是在原list基础上修改
  2. a=[ '5', '4', '8']
  3. a.sort(reverse= True)
  4. #print(a)
  5. a=[ 's', 'f', 's']
  6. #print(len(a))
  7. #for i in range(len(a)):
  8. # print(i)
  9. # range是左闭右开的区间
  10. #for i in range(1,len(a)):
  11. # print(i)
  12. # list有几种删除方法,remove删除第一个,pop按照索引删 ,del根据索引范围删
  13. strs=[ 1, 2, 3, 4, 5, 6]
  14. #print(strs)
  15. strs.remove( 2)
  16. #print(strs)
  17. strs=[ 1, 2, 3, 4, 5, 6]
  18. strs.pop( 1)
  19. #print(strs)
  20. strs=[ 1, 2, 3, 4, 5, 6]
  21. del strs[ 2: 4]
  22. #print(strs)
  23. b=[ '5', '4', '8']
  24. b.reverse()
  25. #print(b)
  26. # list和string的互转
  27. mm= 'sfsfsafsaf'
  28. # print(list(mm))
  29. nn=[ 's', 'f', 's', 'f', 's', 'a', 'f', 's', 'a', 'f']
  30. # print(''.join(nn))
  31. # 字符替换
  32. def replaceSpace(s):
  33. return s.replace( ' ', '%20')
  34. #print('jsst'.split('ss'))
  35. aaa=[ '8', '5', '4']
  36. bbb=[ '8', '4', '5']
  37. aaa.extend(bbb)
  38. #print(''.join(aaa))
  39. #print(aaa)
  40. # input的格式问题测试
  41. def input_test():
  42. age_str= input( "Please input your age: ")
  43. if age_str.isdigit():
  44. return int(age_str)
  45. else:
  46. print( '输入不是数字,请重新输入!')
  47. return
  48. #print(input_test())
  49. sdfaf=[ 4, 12, 12, 15, 23, 32, 43]
  50. #print(sdfaf.pop(0),sdfaf)
  51. # list中的替换操作
  52. aaa=[ '黑色', '红色', '白色', '黑色']
  53. bbb=[ '黄色' if i == '黑色' else i for i in aaa]
  54. # 给定一个字符串,找到其中只出现一次的字符
  55. stams= 'jfaljgdiwogjajflda'
  56. print( ''.join([i for i in list(stams) if list(stams).count(i)== 1]))
  57. # 给定一个字符串,找到不重复的值
  58. stasss= 'jfaljgdiwogjajflda'
  59. #print(list(stasss))
  60. temp=[]
  61. for i in list(stasss):
  62. if i not in temp:
  63. temp.append(i)
  64. print( ''.join(temp))

map函数及其他

map、fliter、reduce等函数常用匿名函数等操作;


  
  1. # map 函数,map函数可以传递匿名函数
  2. def test_func(a):
  3. return a+ 'b'
  4. #print(list(map(test_func,['xx','djkd'])))
  5. #print(list(map(lambda a: a+'b',['xx','djkd'])))
  6. # fliter 过滤函数
  7. def test_funt(b):
  8. return b>= 3
  9. #print(list(filter(test_funt,[1,2,3,4])))
  10. # 也可以用foreach
  11. # a=[elem for elem in [1,2,3,4] if elem>2]
  12. # print(list(elem for elem in [1,2,3,4] if elem>2))

 简单的几个算法题

罗列几个常用算法题:走楼梯、排序的组合数


  
  1. # 递归的楼梯走法
  2. # stairs 阶梯,可以走1步,也可以走2步,问总共有几种走法?
  3. def go_staris(stairs):
  4. if stairs== 1:
  5. return 1
  6. elif stairs== 2:
  7. return 2
  8. else:
  9. return go_staris(stairs -1)+go_staris(stairs -2)
  10. print (go_staris( 10))
  11. # 输入一个数,得到1到这个数的所有排列组合;
  12. import itertools
  13. def num_one():
  14. num=input( '请输入一个数:')
  15. listone=list(str(elem+ 1) for elem in range(int(num)))
  16. # print(listone)
  17. for p in itertools.permutations(listone):
  18. print( ''.join(list(p)))
  19. num_one()
  20. # 数组中找数
  21. def find(target, array):
  22. a= 0
  23. for item in array:
  24. if(item in array):
  25. a=a+ 1
  26. if(a== 0):
  27. return False
  28. else:
  29. return True
  30. # 字符替换
  31. def replaceSpace(s):
  32. return s.replace( ' ', '%20')

面向对象、链表、二叉树

链表全部


  
  1. # python 实现链表
  2. class Node():
  3. def __init__(self,val):
  4. self.data = val
  5. self.next = 0
  6. class LinkList():
  7. def __init__(self):
  8. self.head = 0
  9. def __getitem__(self, key):
  10. if self.is_empty():
  11. print ( 'linklist is empty.')
  12. return
  13. elif key < 0 or key > self.getlength():
  14. print ( 'the given key is error')
  15. return
  16. else:
  17. return self.getitem(key)
  18. def __setitem__(self, key, value):
  19. if self.is_empty():
  20. print ( 'linklist is empty.')
  21. return
  22. elif key < 0 or key > self.getlength():
  23. print ( 'the given key is error')
  24. return
  25. else:
  26. self.delete(key)
  27. return self.insert(key)
  28. def initlist(self,data):
  29. self.head = Node(data[ 0])
  30. p = self.head
  31. for i in data[ 1:]:
  32. p.next = Node(i)
  33. p = p.next
  34. def getlength(self):
  35. p = self.head
  36. length = 0
  37. while p!= 0:
  38. length+= 1
  39. p = p.next
  40. return length
  41. def is_empty(self):
  42. if self.getlength() == 0:
  43. return True
  44. else:
  45. return False
  46. def clear(self):
  47. self.head = 0
  48. def append(self,item):
  49. q = Node(item)
  50. if self.head == 0:
  51. self.head = q
  52. else:
  53. p = self.head
  54. while p.next!= 0:
  55. p = p.next
  56. p.next = q
  57. def getitem(self,index):
  58. if self.is_empty():
  59. print ( 'Linklist is empty.')
  60. return
  61. j = 0
  62. p = self.head
  63. while p.next!= 0 and j <index:
  64. p = p.next
  65. j+= 1
  66. if j ==index:
  67. return p.data
  68. else:
  69. print ( 'target is not exist!')
  70. def insert(self,index,item):
  71. if self.is_empty() or index< 0 or index >self.getlength():
  72. print ()
  73. return
  74. if index == 0:
  75. q = Node(item,self.head)
  76. self.head = q
  77. p = self.head
  78. post = self.head
  79. j = 0
  80. while p.next!= 0 and j<index:
  81. post = p
  82. p = p.next
  83. j+= 1
  84. if index ==j:
  85. q = Node(item,p)
  86. post.next = q
  87. q.next = p
  88. def delete(self,index):
  89. if self.is_empty() or index< 0 or index >self.getlength():
  90. print ( 'Linklist is empty.')
  91. return
  92. if index == 0:
  93. q = Node(item,self.head)
  94. self.head = q
  95. p = self.head
  96. post = self.head
  97. j = 0
  98. while p.next!= 0 and j<index:
  99. post = p
  100. p = p.next
  101. j+= 1
  102. if index ==j:
  103. post.next = p.next
  104. def index(self,value):
  105. if self.is_empty():
  106. print ( 'Linklist is empty.')
  107. return
  108. p = self.head
  109. i = 0
  110. while p.next!= 0 and not p.data ==value:
  111. p = p.next
  112. i+= 1
  113. if p.data == value:
  114. return i
  115. else:
  116. return -1
  117. l = LinkList()
  118. #l.initlist([1,2,3,4,5])
  119. #print(l.getlength())

链表简易版


  
  1. class Node:
  2. def __init__(self,val):
  3. self.val=val
  4. self.next= None
  5. class List:
  6. def __init__(self):
  7. self.head= None
  8. self.vals=[]
  9. def init_list(self):
  10. length=int(input( '请输入一个链表长度:\n'))
  11. items=[]
  12. for i in range(length):
  13. items.append(int(input( '请输入链表的值:\n')))
  14. self.vals=items
  15. #print(self.vals)
  16. self.head=Node(items[ 0])
  17. temp=self.head
  18. for i in range( 1,length -1):
  19. temp.next=Node(items[i])
  20. temp=temp.next
  21. def append_node(self,val):
  22. temp=self.head
  23. q=Node(val)
  24. if temp== None:
  25. temp=q
  26. else:
  27. while temp.next!= None:
  28. temp=temp.next
  29. temp.next=q
  30. def extend_list(self,somelist):
  31. temp=self.vals
  32. temp.extend(somelist.vals)
  33. newlists=List()
  34. newlists.head=Node(temp[ 0])
  35. p=newlists.head
  36. for i in range( 1,len(temp)):
  37. p.next=Node(temp[i])
  38. p=p.next
  39. print(newlists.vals)
  40. ListOne=List()
  41. ListOne.init_list()
  42. ListTwo=List()
  43. ListTwo.init_list()
  44. ListOne.extend_list(ListTwo)
  45. #print(ListOne.vals)
  46. #print(ListTwo.vals)

二叉树

 


  
  1. #二叉树查找 相当于队列
  2. class Node(object):
  3. """定义节点"""
  4. def __init__(self,item):
  5. self.elem = item
  6. self.lchild = None
  7. self.rchild = None
  8. class Tree(object):
  9. """二叉树"""
  10. def __init__(self):
  11. self.root = None
  12. def add(self,item):
  13. """为树添加节点"""
  14. node = Node(item)
  15. if self.root is None:
  16. self.root = node
  17. return
  18. queue = [self.root]
  19. while queue:
  20. cur_node = queue.pop( 0)
  21. if cur_node.lchild is None:
  22. cur_node.lchild = node
  23. return
  24. else:
  25. queue.append(cur_node.lchild)
  26. if cur_node.rchild is None:
  27. cur_node.rchild = node
  28. return
  29. else:
  30. queue.append(cur_node.rchild)
  31. # 广度优先遍历
  32. def breadth_travel(self):
  33. """广度优先遍历"""
  34. if self.root is None:
  35. return
  36. queue = [self.root]
  37. while queue:
  38. cur_node = queue.pop( 0)
  39. print(cur_node.elem,end= '')
  40. if cur_node.lchild is not None:
  41. queue.append(cur_node.lchild)
  42. if cur_node.rchild is not None:
  43. queue.append(cur_node.rchild)
  44. # 先序遍历
  45. def preorder(self,node):
  46. """先序遍历"""
  47. if node is None:
  48. return
  49. print(node.elem,end = '')
  50. self.preorder(node.lchild)
  51. self.preorder(node.rchild)
  52. # 中序遍历
  53. def inorder(self,node):
  54. """中序遍历"""
  55. if node is None:
  56. return
  57. self.inorder(node.lchild)
  58. print(node.elem,end = '')
  59. self.inorder(node.rchild)
  60. # 后序遍历
  61. def postorder(self,node):
  62. """后序遍历"""
  63. if node is None:
  64. return
  65. self.postorder(node.lchild)
  66. self.postorder(node.rchild)
  67. print(node.elem,end = '')

 


转载:https://blog.csdn.net/yezonggang/article/details/114945455
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场