1.输出前50个素数
count=0
x=2
while count<50:
for i in range(2,x):
if x % i==0:
break
else:
print(x),
count+=1
x+=1
2.判断一个数是否为回文数
num=int(input('please enter an number'))
num1=num
num2=0
while num!=0:
num2=int(num2*10+num%10)
num=int(num/10)
if num1==num2:
print('yes')
else:
print('no')
3.二分法求一个数得平方根(考虑x<0和x<1的情况)
x1=float(input('enter an number'))
if x1>=1:
x=x1
low=0
high=x
elif x1>=0 and x<1:
x=x1
low=0
high=1
else:
x=-x1
if x>=1:
low=0
high=x
elif x>=0 and x<1:
low=0
high=1
guess=(low+high)/2
while (abs(guess**2-x)>1e-4):
if guess**2>x:
high=guess
else:
low=guess
guess=(low+high)/2
if x1>=0:
print(guess)
else :
print(guess,'j')
4.选择排序法:版本1:(找到列表中最小的值,并删除它,之后将其放到指定的位置)
def selection_sort(lst):
for i in range(len(lst)):
min_index=i
for j in range(i+1,len(lst)):
if lst[j]<lst[min_index]:
min_index=j
lst.insert(i,lst.pop(min_index))
lst=[10,5,8,13]
selection_sort(lst)
print(lst)
5.选择排序法:版本2
def swap(lst,i,j): #交换list里的第i和j位
tmp=lst[i]
lst[i]=lst[j]
lst[j]=tmp
def selection_sort_v2(lst):
for i in range(len(lst)):
min_index=i
for j in range(i+1,len(lst)):
if lst[j]<lst[min_index]:
min_index=j #通过两重循环,找到最小的值
swap(lst,i,min_index)
lst=[10,5,8,13]
selection_sort_v2(lst)
print(lst)
6.冒泡排序法
def swap(lst,i,j): #交换list里的第i和j位
tmp=lst[i]
lst[i]=lst[j]
lst[j]=tmp
def bubble_sort(lst):
exchanged = True
top = len(lst)-1
while exchanged:
exchanged = False
for i in range(top):
if lst[i]>lst[i+1]:
swap(lst,i,i+1)
exchanged = True
top-=1
lst=[12,10,5,8,13]
bubble_sort(lst)
print(lst)