python 部分笔试代码题整理

生成器实现斐波那契

def Fob(n):
    count=1
    pre=0
    nex=1
    while count<n:
        pre,nex=nex,pre+nex
        count+=1
    yield pre

fob=Fob(8)
for v in fob:
    print(v)

迭代器实现斐波那契

class myFactorial:
    def __init__(self, n):
        self.n = n
        self.a = 0
        self.b = 1
        self.count = 0

    def __iter__(self):
        return self

    def __next__(self):
        value = self.a
        self.a, self.b = self.b, self.a + self.b
        self.count += 1
        if self.count > self.n:
            raise StopIteration
        return value


fei = myFactorial(10)
for v in fei:
    print(v)

单例模式的实现

class F(object):
    __isinstance = None
    __hasinit = False
    
    def __init__(self):
        if not __hasinit:
            self.__hasinit = True
    
    def __next__(cls,*args,**kwargs):
        if not __isinstance:
            cls.__isinstance = object.__new__(cls)
        return cls.__instance

统计字符出现的次数

import itertools
l = [(k, len(list(g))) for k, g in itertools.groupby('qqawwwzz')]
print(l)

执行结果:
在这里插入图片描述

冒泡排序

def maopao(li:list):
    for v in range(len(li)-1,0,-1):
        for i in range(v):
            if li[i]<=li[i+1]:
                li[i],li[i+1]=li[i+1],li[i]

li = [1,3,2,14,23,11]
maopao(li)

快速排序

def quick(li:list):
    less = []
    equal = []
    biger = []
    
    if len(li)>1:
        pivot = li[0]
        for v in li:
            if v < pivot:
                less.append(v)
            elif v == pivot:
                equal.append(v)
            else:
                biger.append(v)
        return quick(less)+equal+quick(biger)
    return li

lis = [1,4,2,34,23,12]
lists = quick(lis)
lists

猜你喜欢

转载自blog.csdn.net/weixin_43958804/article/details/87922608