慕课 哈尔滨工业大学 python入门知识点总结

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)

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值