python基础算法

面向对象三大基本特征: 封装,继承,多态

二分法/折半 查找:若存在返回下标,若不存在,返回-1

a = [1, 2, 3, 4, 5, 7, 9, 11, 34, 43, 167, 345, 678, 899]
s = 5
t= -1
length = len(a)
start = 0
end =length -1
while end >= start:
    half = (end+start)//2
    if a[half] > s:
        end = half
    elif a[half] < s :
        start = half + 1
    else:
        t = half
        break
print(t)

九九乘法表

for  i in range(1,10):
    for j in range(1,i+1):
        print(i,"X",j,"=",j*i,end="\t")
    print()

冒泡排序

a = [3,5,7,1,4,34,678,2,167,899,43,11,9,345]
b = len(a)
for i in range(b-1,0,-1):
    for j in range(i):
        if a[j] > a[j+1]:
            a[j],a[j+1] =a[j+1],a[j]
print(a)

1到100内的和

s = 0
for i  in range(1,101):
    s= s+ i
print(s)

替换

a = "我是xxx,我来自wwww"
a = a.replace("我是xxx,我来自wwww","我是小明来自上海")
print(a)

逢七过一

for i in range(1000):
    if(i % 7 == 0):
        print("过")
    elif(i % 10 == 7):
        print("过")
    else:
        print(i)

逢七过二

for i in range(1000):
    if(i % 7 == 0):
        print("过")
        continue
    if(i % 10 == 7):
        print("过")
        continue
    print(i)

找出200以内的回数

#找出200以内的"回数"(即:从左向右,从右向左,都是一样的数,比如:131, 141)
def is_palindrome(n):
    if n < 10:
        return True
    s = str(n)
    for i in range(0, int(len(s) / 2)):
        if s[i] == s[-i - 1]:
            return True
    return False

print(list(filter(is_palindrome, range(1, 201))))


# 或者


def is_palindrome(n):
    s1 = str(n)
    s2 = list(reversed(s1))
    return list(s1) == s2


print(list(filter(is_palindrome, range(1, 201))))

你可能感兴趣的:(python基础算法)