本文探讨使用python优雅进行acm刷题.acm模式相比于传统的核心代码模式需要开发者自行处理程序的输入和输出.本文详细讲解常规的处理方式.
input
首先想到的是比较常见的处理输入的函数是input,如果使用input来处理输入,其代码如下:
def test_input():
while True:
try:
raw_input = input()
print(f"raw line: {raw_input}")
# 实际代码
except EOFError:
print('eof happened and execution ended')
break
input函数需要注意两个点.第一,它会自动清理一行末尾的换行符;第二,遇到EOF(unix系统下为ctrl+D)会抛出EOFError.因此处理的时候则需要捕获EOFError.
sys.stdin
另一种处理输入的方式是使用sys.stdin,代码如下:
def test_stdin():
# EOF不会抛出异常,这里直接终止循环
for line in sys.stdin:
# 手动处理尾部换行符
act_line = line.rstrip('\n')
print(f"raw line: {act_line}")
使用sys.stdin是一种更常见的方式,同样需要注意两点:第一,sys.stdin不会处理末尾换行符,所以需要使用rstrip函数手动取出;第二,sys.stdin不需要额外去处理EOF,代码中遇到EOF则终止循环,是一种acm模式下更适配的处理方式.
1935

被折叠的 条评论
为什么被折叠?



