python3刷USACO题库 Sum the Numbers (map(), list comprehension)

in #acm6 years ago (edited)

USACO是美国计算机奥林匹克竞赛在线题库,提供了一个从零开始入门的系列题目,分为6个章节,每章节有4-5个部分。每个章节里的题目集中于一种算法的训练。你只有完成了前面的题目,后面的题目才会开放给你。另外,不同于其他OJ,USACO是从文件中读取输入,所以我们在编写代码的时候,要注意从文件中读取数据而不是控制台。同时在提交代码的时候,需要在代码最前面加上 你的ID:
/*
ID:帐号
PROG:做的题的名字
LANG:C++
*/
这些都和正式的ACM比赛很一致。

Sum the Numbers是最开始的用于测试递交系统的题目。他给你一个源代码,你需要学会在这份源代码前面加上如上所述的题头,然后使用网页的上传按钮递交答案。

这个题目本身很简单,和TK的前1000-1010类似:
输入是一行两个用空格隔开的整数,从test.in文件中读取;
输出是如山两个整数的和,写入test.out文件。

题目给出的python3代码为

fin = open ('test.in', 'r')
fout = open ('test.out', 'w')
x,y = map(int, fin.readline().split())
sum = x+y
fout.write (str(sum) + '\n')
fout.close()

其中map()的用处:x,y需要把输入转换为int形式才能做计算。而fin.readline().split()返回一个列表,但int()类型转换不支持列表。所以需要一个遍历列表的命令,即list comprehension:

x, y = [int(a) for a in fin.readline().split()]

map()的作用类似上述命令,它有两个参数,第一个参数为一个操作,第二个为一个序列,比如列表。map()的作用就是把第一个操作应用于后一个列表。

附C和C++代码:

/*
ID: your_id_here
LANG: C
TASK: test
*/
#include <stdio.h>
main () {
    FILE *fin  = fopen ("test.in", "r");
    FILE *fout = fopen ("test.out", "w");
    int a, b;
    fscanf (fin, "%d %d", &a, &b);  /* the two input integers */
    fprintf (fout, "%d\n", a+b);
    exit (0);
}
/*
ID: your_id_here
TASK: test
LANG: C++                 
*/
/* LANG can be C++11 or C++14 for those more recent releases */
#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main() {
    ofstream fout ("test.out");
    ifstream fin ("test.in");
    int a, b;
    fin >> a >> b;
    fout << a+b << endl;
    return 0;
}

参考文献:

  1. https://www.python-course.eu/python3_lambda.php
  2. https://stackoverflow.com/questions/1303347/getting-a-map-to-return-a-list-in-python-3-x

Coin Marketplace

STEEM 0.28
TRX 0.12
JST 0.033
BTC 71148.50
ETH 3780.07
USDT 1.00
SBD 3.78