用Python在牛客刷题美滋滋,但基础知识不能只靠编译器提示,之前博客已经有对Python基础总结,趁机再把基础知识复习一遍吧,满足基本地算法刷题需要;
目录
字符串及方法
包含字符串的常用操作:分割、替换、去空格、根据索引输出等
-
# 字符串分割
-
orgin_str=
'lsajgajga af jaslf jas alfjal sdsfarfa a jaslfja '
-
list_str=orgin_str.split(
' ')
-
#print(type(list_str))
-
# replace 替换后返回新的字符串,而非在原始str上做替换;
-
str_two=orgin_str.replace(
'af',
'yzg')
-
#print(str_two,orgin_str)
-
#print(str_two.find('yzg'))
-
# join方法是str方法,把list和tuple都连接在一起,跟split反着来。
-
str_three=
'b'
-
#print(str_three.join(['d','r']))
-
# 去空格
-
xxx=
' flajfla sdsa '
-
#print(xxx,xxx.lstrip(),xxx.lstrip())
-
#print("原始数据是%s去掉空格后是%s" %xxx,%xxx)
-
# 定位某个元素的第一个位置
-
lista=[
1,
2,
3,
4]
-
#print(lista.index(1))
-
-
sssstr =
'12345'
-
#print(sssstr[1:3])
-
#print("下面输出一串数字:%s" %str)
-
#print("原始数据是:%s,去掉空格后是:%s" %(xxx,xxx))
-
-
# 字符串反转
-
strsda=
'asdfghjkl'
-
a=list(strsda)
-
a.reverse()
-
#print(''.join(a))
list列表及方法
包含list的反转、排序、遍历、删除、检索、str转换等;
-
-
# sort()和reverse()把list排序和反转就是在原list基础上修改
-
a=[
'5',
'4',
'8']
-
a.sort(reverse=
True)
-
#print(a)
-
-
a=[
's',
'f',
's']
-
#print(len(a))
-
#for i in range(len(a)):
-
# print(i)
-
-
# range是左闭右开的区间
-
#for i in range(1,len(a)):
-
# print(i)
-
-
# list有几种删除方法,remove删除第一个,pop按照索引删 ,del根据索引范围删
-
strs=[
1,
2,
3,
4,
5,
6]
-
#print(strs)
-
strs.remove(
2)
-
#print(strs)
-
strs=[
1,
2,
3,
4,
5,
6]
-
strs.pop(
1)
-
#print(strs)
-
strs=[
1,
2,
3,
4,
5,
6]
-
del strs[
2:
4]
-
#print(strs)
-
-
b=[
'5',
'4',
'8']
-
b.reverse()
-
#print(b)
-
# list和string的互转
-
mm=
'sfsfsafsaf'
-
# print(list(mm))
-
nn=[
's',
'f',
's',
'f',
's',
'a',
'f',
's',
'a',
'f']
-
# print(''.join(nn))
-
-
-
# 字符替换
-
def replaceSpace(s):
-
return s.replace(
' ',
'%20')
-
-
#print('jsst'.split('ss'))
-
aaa=[
'8',
'5',
'4']
-
bbb=[
'8',
'4',
'5']
-
aaa.extend(bbb)
-
#print(''.join(aaa))
-
#print(aaa)
-
-
# input的格式问题测试
-
def input_test():
-
age_str= input(
"Please input your age: ")
-
if age_str.isdigit():
-
return int(age_str)
-
else:
-
print(
'输入不是数字,请重新输入!')
-
return
-
#print(input_test())
-
-
-
sdfaf=[
4,
12,
12,
15,
23,
32,
43]
-
#print(sdfaf.pop(0),sdfaf)
-
# list中的替换操作
-
aaa=[
'黑色',
'红色',
'白色',
'黑色']
-
bbb=[
'黄色'
if i ==
'黑色'
else i
for i
in aaa]
-
-
# 给定一个字符串,找到其中只出现一次的字符
-
stams=
'jfaljgdiwogjajflda'
-
print(
''.join([i
for i
in list(stams)
if list(stams).count(i)==
1]))
-
-
# 给定一个字符串,找到不重复的值
-
stasss=
'jfaljgdiwogjajflda'
-
#print(list(stasss))
-
temp=[]
-
for i
in list(stasss):
-
if i
not
in temp:
-
temp.append(i)
-
print(
''.join(temp))
map函数及其他
map、fliter、reduce等函数常用匿名函数等操作;
-
# map 函数,map函数可以传递匿名函数
-
def test_func(a):
-
return a+
'b'
-
-
#print(list(map(test_func,['xx','djkd'])))
-
#print(list(map(lambda a: a+'b',['xx','djkd'])))
-
# fliter 过滤函数
-
def test_funt(b):
-
return b>=
3
-
-
#print(list(filter(test_funt,[1,2,3,4])))
-
# 也可以用foreach
-
# a=[elem for elem in [1,2,3,4] if elem>2]
-
# print(list(elem for elem in [1,2,3,4] if elem>2))
简单的几个算法题
罗列几个常用算法题:走楼梯、排序的组合数
-
# 递归的楼梯走法
-
# stairs 阶梯,可以走1步,也可以走2步,问总共有几种走法?
-
def go_staris(stairs):
-
if stairs==
1:
-
return
1
-
elif stairs==
2:
-
return
2
-
else:
-
return go_staris(stairs
-1)+go_staris(stairs
-2)
-
print (go_staris(
10))
-
-
# 输入一个数,得到1到这个数的所有排列组合;
-
import itertools
-
def num_one():
-
num=input(
'请输入一个数:')
-
listone=list(str(elem+
1)
for elem
in range(int(num)))
-
# print(listone)
-
for p
in itertools.permutations(listone):
-
print(
''.join(list(p)))
-
num_one()
-
-
# 数组中找数
-
def find(target, array):
-
a=
0
-
for item
in array:
-
if(item
in array):
-
a=a+
1
-
if(a==
0):
-
return
False
-
else:
-
return
True
-
-
# 字符替换
-
def replaceSpace(s):
-
return s.replace(
' ',
'%20')
面向对象、链表、二叉树
链表全部
-
# python 实现链表
-
class Node():
-
def __init__(self,val):
-
self.data = val
-
self.next =
0
-
-
class LinkList():
-
def __init__(self):
-
self.head =
0
-
-
def __getitem__(self, key):
-
if self.is_empty():
-
print (
'linklist is empty.')
-
return
-
elif key <
0
or key > self.getlength():
-
print (
'the given key is error')
-
return
-
else:
-
return self.getitem(key)
-
-
def __setitem__(self, key, value):
-
if self.is_empty():
-
print (
'linklist is empty.')
-
return
-
elif key <
0
or key > self.getlength():
-
print (
'the given key is error')
-
return
-
else:
-
self.delete(key)
-
return self.insert(key)
-
-
def initlist(self,data):
-
self.head = Node(data[
0])
-
p = self.head
-
for i
in data[
1:]:
-
p.next = Node(i)
-
p = p.next
-
-
def getlength(self):
-
p = self.head
-
length =
0
-
while p!=
0:
-
length+=
1
-
p = p.next
-
return length
-
-
def is_empty(self):
-
if self.getlength() ==
0:
-
return
True
-
else:
-
return
False
-
-
def clear(self):
-
self.head =
0
-
-
-
def append(self,item):
-
q = Node(item)
-
if self.head ==
0:
-
self.head = q
-
else:
-
p = self.head
-
while p.next!=
0:
-
p = p.next
-
p.next = q
-
-
-
def getitem(self,index):
-
if self.is_empty():
-
print (
'Linklist is empty.')
-
return
-
j =
0
-
p = self.head
-
-
while p.next!=
0
and j <index:
-
p = p.next
-
j+=
1
-
-
if j ==index:
-
return p.data
-
else:
-
print (
'target is not exist!')
-
-
def insert(self,index,item):
-
if self.is_empty()
or index<
0
or index >self.getlength():
-
print ()
-
return
-
-
if index ==
0:
-
q = Node(item,self.head)
-
self.head = q
-
-
p = self.head
-
post = self.head
-
j =
0
-
while p.next!=
0
and j<index:
-
post = p
-
p = p.next
-
j+=
1
-
-
if index ==j:
-
q = Node(item,p)
-
post.next = q
-
q.next = p
-
-
-
def delete(self,index):
-
if self.is_empty()
or index<
0
or index >self.getlength():
-
print (
'Linklist is empty.')
-
return
-
if index ==
0:
-
q = Node(item,self.head)
-
-
self.head = q
-
-
p = self.head
-
post = self.head
-
j =
0
-
while p.next!=
0
and j<index:
-
post = p
-
p = p.next
-
j+=
1
-
-
if index ==j:
-
post.next = p.next
-
-
def index(self,value):
-
if self.is_empty():
-
print (
'Linklist is empty.')
-
return
-
p = self.head
-
i =
0
-
while p.next!=
0
and
not p.data ==value:
-
p = p.next
-
i+=
1
-
-
if p.data == value:
-
return i
-
else:
-
return
-1
-
-
-
l = LinkList()
-
#l.initlist([1,2,3,4,5])
-
#print(l.getlength())
链表简易版
-
class Node:
-
def __init__(self,val):
-
self.val=val
-
self.next=
None
-
-
-
class List:
-
def __init__(self):
-
self.head=
None
-
self.vals=[]
-
-
def init_list(self):
-
length=int(input(
'请输入一个链表长度:\n'))
-
items=[]
-
for i
in range(length):
-
items.append(int(input(
'请输入链表的值:\n')))
-
self.vals=items
-
#print(self.vals)
-
self.head=Node(items[
0])
-
temp=self.head
-
for i
in range(
1,length
-1):
-
temp.next=Node(items[i])
-
temp=temp.next
-
def append_node(self,val):
-
temp=self.head
-
q=Node(val)
-
if temp==
None:
-
temp=q
-
else:
-
while temp.next!=
None:
-
temp=temp.next
-
temp.next=q
-
-
def extend_list(self,somelist):
-
temp=self.vals
-
temp.extend(somelist.vals)
-
newlists=List()
-
newlists.head=Node(temp[
0])
-
p=newlists.head
-
for i
in range(
1,len(temp)):
-
p.next=Node(temp[i])
-
p=p.next
-
print(newlists.vals)
-
-
ListOne=List()
-
ListOne.init_list()
-
-
ListTwo=List()
-
ListTwo.init_list()
-
-
ListOne.extend_list(ListTwo)
-
#print(ListOne.vals)
-
#print(ListTwo.vals)
二叉树
-
#二叉树查找 相当于队列
-
class Node(object):
-
"""定义节点"""
-
def __init__(self,item):
-
self.elem = item
-
self.lchild =
None
-
self.rchild =
None
-
class Tree(object):
-
"""二叉树"""
-
def __init__(self):
-
self.root =
None
-
-
def add(self,item):
-
"""为树添加节点"""
-
node = Node(item)
-
if self.root
is
None:
-
self.root = node
-
return
-
-
queue = [self.root]
-
while queue:
-
cur_node = queue.pop(
0)
-
if cur_node.lchild
is
None:
-
cur_node.lchild = node
-
return
-
else:
-
queue.append(cur_node.lchild)
-
if cur_node.rchild
is
None:
-
cur_node.rchild = node
-
return
-
else:
-
queue.append(cur_node.rchild)
-
# 广度优先遍历
-
def breadth_travel(self):
-
"""广度优先遍历"""
-
if self.root
is
None:
-
return
-
queue = [self.root]
-
while queue:
-
cur_node = queue.pop(
0)
-
print(cur_node.elem,end=
'')
-
if cur_node.lchild
is
not
None:
-
queue.append(cur_node.lchild)
-
if cur_node.rchild
is
not
None:
-
queue.append(cur_node.rchild)
-
# 先序遍历
-
def preorder(self,node):
-
"""先序遍历"""
-
if node
is
None:
-
return
-
print(node.elem,end =
'')
-
self.preorder(node.lchild)
-
self.preorder(node.rchild)
-
# 中序遍历
-
def inorder(self,node):
-
"""中序遍历"""
-
if node
is
None:
-
return
-
self.inorder(node.lchild)
-
print(node.elem,end =
'')
-
self.inorder(node.rchild)
-
# 后序遍历
-
def postorder(self,node):
-
"""后序遍历"""
-
if node
is
None:
-
return
-
self.postorder(node.lchild)
-
self.postorder(node.rchild)
-
print(node.elem,end =
'')
转载:https://blog.csdn.net/yezonggang/article/details/114945455
查看评论