Review of Codeforces 5A and 5B(Python)

本文介绍了两种处理输入的方法:使用sys.stdin和异常处理(try...catch)。通过示例代码展示了如何使用这些方法来解决具体问题,包括统计ChatServer的外发流量及实现文本居中对齐。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

5A. Chat Server's Outgoing Traffic

Seems like a simple task. However, you may find it is difficult to tell the determination of the input. There are two method: first one is using sys.stdin. you may need to learn how to use sys model. The second method is using exeption method(try...catch)

source code as follows:

v, m = 0, 0
while True:
    try:
        temp = raw_input()
    except :
        break
    if temp[0] == '+':
        m += 1
    elif temp[0] == '-':
        m -= 1
    else:
        i = temp.index(':')
        v += len(temp[i+1::]) * m

print v

5B Center Alignment

if you have the exps of UI, this problem is easy to solve. also use try...catch to deal with the input, source code as follows:

v = []

while True:
    try:
        s = raw_input()
    except :
        break
    l = len(s)
    v.append([s, l])

vm = v[:]
vm.sort(key = lambda x : x[1])
width = vm[-1][1] + 2
cc = 0
print '*' * width
for i in xrange(len(v)):
    temp = v[i]
    if (width - temp[1]) % 2:
        if cc % 2 == 0:
            temp[0] += ' '
            temp[1] += 1
            cc += 1
        else :
            temp[0] = ' ' + temp[0]
            temp[1] += 1
            cc += 1
    sw = (width - temp[1]) / 2
    lw = '*' + ' '*(sw-1)
    rw = ' '*(sw-1) + '*'
    temp[0] = lw + temp[0] + rw
    print temp[0]
print '*' * width



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值