蓝桥杯国赛前一晚知识点准备(十六届python)

许愿国三

1、判断文件最后一行终止输入

复制代码
with open('example.txt', 'r') as file:
    while True:                 # 开始一个无限循环
        try:
            line = file.readline()  # 试图读取文件的一行
            if line:               # 如果读取到了一行(不是文件末尾)
                print(line.strip())  # 打印这行内容(去掉首尾空白字符)
                # 在这里可以进行其他输入处理操作
            else:                  # 如果没有读取到内容(文件末尾)
                break              # 跳出循环
        except EOFError:           # 捕获文件末尾错误(EOFError)
            print("已到达文件末尾,终止输入")
            break                  # 跳出循环

2、输出

复制代码
打印小数:print("{:.2f}".format(x))
print("%.2f"%cnt)
print(round(x,2))
打印字符串:print(" ".join(parts))
print("%s"%x)

3、模拟栈(eg:AcWing - 算法基础课

复制代码
dic={'(':0,'+':1,'-':1,'*':2,'/':2}
op=[]
num=[]

def new_eval():
    b=num.pop()
    a=num.pop()
    c=op.pop()
    x=0
    if c=='+':
        x=a+b
    elif c=='-':
        x=a-b
    elif c=='*':
        x=a*b
    else: x=int(a/b)
    num.append(x)

a=input()
n=len(a)

i=0
while i<n:
    c=a[i]
    if c.isdigit():
        j=i
        x=0
        while j<n and a[j].isdigit():
            x=x*10+int(a[j])
            j+=1
        i=j-1
        num.append(x)
    elif c=='(':
        op.append(c)
    elif c==')':
        while op[-1]!='(':
            new_eval()
        op.pop()
    else:
        while len(op) and dic[op[-1]]>=dic[c]:
            new_eval()
        op.append(c)
    i+=1
while len(op):
    new_eval()
print(num[-1])

4、二分(eg:AcWing - 算法基础课

复制代码
n,m=map(int,input().split())

a=[int(x) for x in input().split()]
n=[int(x) for x in input().split()]

while m:
    m-=1
    q=int(input())
    l=0
    r=n-1
    
    while l<r:
        mid=l+r>>1
        if q<=a[mid]:
            r=mid
        else: l=mid+1
    if a[l]!=q:
        print("-1 -1")
    else:
        print(r,end=' ')
        l=0
        r=n-1
        while l<r:
            mid=l+r+1>>1
            if q>=a[mid]:
                l=mid
            else:
                r=mid-1
        print(r)
相关推荐
阿蒙Amon1 小时前
TypeScript学习-第7章:泛型(Generic)
javascript·学习·typescript
睡美人的小仙女1271 小时前
Threejs加载环境贴图报错Bad File Format: bad initial token
开发语言·javascript·redis
fanruitian1 小时前
uniapp android开发 测试板本与发行版本
前端·javascript·uni-app
rayufo1 小时前
【工具】列出指定文件夹下所有的目录和文件
开发语言·前端·python
RANCE_atttackkk1 小时前
[Java]实现使用邮箱找回密码的功能
java·开发语言·前端·spring boot·intellij-idea·idea
摘星编程2 小时前
React Native + OpenHarmony:Timeline垂直时间轴
javascript·react native·react.js
Python 老手3 小时前
Python while 循环 极简核心讲解
java·python·算法
2501_944525543 小时前
Flutter for OpenHarmony 个人理财管理App实战 - 支出分析页面
android·开发语言·前端·javascript·flutter
开源技术3 小时前
如何将本地LLM模型与Ollama和Python集成
开发语言·python
weixin_437044643 小时前
Netbox批量添加设备——堆叠设备
linux·网络·python