上实验,老师讲得太无聊,电脑上只有python还能玩玩,于是我悄悄地敲代码。。
python 删除序列里多余的元素:
>>> a=[1,2,2,2,3,4,5,5,5]
>>> b=set(a)
>>> print(b)
set([1, 2, 3, 4, 5])
>>> b=list(b)
>>> print(b)
output: [1, 2, 3, 4, 5]
冒泡排序:
def bubble_sort(a):
length=len(a)
if length<2:
return a
for i in range(length-1):
for j in range(length-i-1):
if a[j]>a[j+1]:
#t=a[j]
#a[j]=a[j+1]
#a[j+1]=t
a[j],a[j+1]=a[j+1],a[j] #简洁写法
return a
a =[1,5,3,9,6]
print(bubble_sort(a))
output: [1, 3, 5, 6, 9]
关于那个简单的交换:等号右边的a[j+1],a[i]生成元组对象,然后分别赋值给a[i],a[j+1].
逆波兰表达式的计算(例子:(3+5)*2/4):
def cal(p,a,b):
if p=='+':
return a+b
if p=='-':
return a-b
if p=='*':
return a*b
if p=='/':
return a/b
def work(exp):
if len(exp)==0:
return 0
temp=[]
result=0
i=0
x=0
y=0
for i in range(0,len(exp)):
element = exp[i]
if element=='+' or element=='-' or element=='*' or element=='/':
y=temp.pop()
x=temp.pop()
temp.append(cal(element,int(x),int(y)))
else:
temp.append(int(element))
return int(temp.pop())
express=['3','5','+','2','*','4','/']
print(work(express))
output: 4
快速排序的C++写法:
选择开始第一个数字作为基准数字,比他大的放后面,小的放到前面。分治递归处理
#include <cstdio>
using namespace std;
void quicksort(int a[],int left,int right){
if(left>right) return ;
int i=left,j=right,temp=a[left];
while(i!=j){
while(a[j]>=temp&&j>i) j--;
if(j>i) a[i++]=a[j];
while(a[i]<=temp&&j>i) i++;
if(j>i) a[j--]=a[i];
}
a[i]=temp;
quicksort(a,left,i-1);
quicksort(a,i+1,right);
}
int main(){
int a[8]={1,4,2,7,9,5,0,12};
quicksort(a,0,7);
for(int i=0;i<8;i++) printf("%4d",a[i]);
return 0;
}
output:0 1 2 4 5 7 9 12
--------------------------------
Process exited with return value 0
Press any key to continue . . .
python:
def qsort(a):
if len(a)<=1: return a
return qsort([b1 for b1 in a[1:] if b1<a[0]])+a[0:1]+\
qsort([b2 for b2 in a[1:] if b2>=a[0]])
a =[1,4,2,7,9,5,0,12]
print(qsort(a))
output:[0, 1, 2, 4, 5, 7, 9, 12]
注意:a[0:1]和a[0]有类型的差异,前者是数组,后者是int对象