许愿国三
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)