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
  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值