Code Jam - Reverse Words for Python
2014-07-29 15:24
330 查看
和前一篇Store Credit一样,是Africa 2010, Qualification Round的题目,现在用于练习
Problem
给出一个用空格分开的单词列表,每行包括L个字母和W个单词。每行仅包含字母和空格,单词之间的空格有且仅有一个。
Input
第一行给出test case的数量N
接下来N行每行包括一个用空格分开的单词列表
Output
对于每个test case,输出一行“Case #x:",之后在该行以相反的顺序输出给定的单词列表。
Sample
源代码:
方法一:
fin = open('B-large-practice.in', 'r')
fout = open('B-large-practice.out', 'w')
N = int(fin.readline())
for cases in xrange(N):
words = fin.readline().split()
L = len(words)
if L != 1:
for i in xrange(L):
if i >= L - i -1:
break
tmp = words[i]
words[i] = words[L - i -1]
words[L - i -1] = tmp
fout.write("Case #%d:" %(cases + 1))
for i in xrange(L):
fout.write(" %s" %(words[i]))
fout.write("\n")
fin.close()
fout.close()
这道题用Python实现起来比较方便,读入一行数据后,用split方法隔开(默认以空格为间隔符,与题目相吻合),之后将单词顺序返过来即可。
方法二:
也可以在不改变输入的列表的情况下直接用
fout.write("Case #%d:" %(cases + 1))
for i in xrange(L):
fout.write(" %s" %(words[-(i + 1)]))
fout.write("\n")方法得到结果。
Problem
给出一个用空格分开的单词列表,每行包括L个字母和W个单词。每行仅包含字母和空格,单词之间的空格有且仅有一个。
Input
第一行给出test case的数量N
接下来N行每行包括一个用空格分开的单词列表
Output
对于每个test case,输出一行“Case #x:",之后在该行以相反的顺序输出给定的单词列表。
Sample
Input | Output |
3 this is a test foobar all your base | Case #1: test a is this Case #2: foobar Case #3: base your all |
方法一:
fin = open('B-large-practice.in', 'r')
fout = open('B-large-practice.out', 'w')
N = int(fin.readline())
for cases in xrange(N):
words = fin.readline().split()
L = len(words)
if L != 1:
for i in xrange(L):
if i >= L - i -1:
break
tmp = words[i]
words[i] = words[L - i -1]
words[L - i -1] = tmp
fout.write("Case #%d:" %(cases + 1))
for i in xrange(L):
fout.write(" %s" %(words[i]))
fout.write("\n")
fin.close()
fout.close()
这道题用Python实现起来比较方便,读入一行数据后,用split方法隔开(默认以空格为间隔符,与题目相吻合),之后将单词顺序返过来即可。
方法二:
也可以在不改变输入的列表的情况下直接用
fout.write("Case #%d:" %(cases + 1))
for i in xrange(L):
fout.write(" %s" %(words[-(i + 1)]))
fout.write("\n")方法得到结果。
相关文章推荐
- (code jam)Problem B. Reverse Words
- [leetcode]Reverse Words in a String @ Python
- [leetcode, python] Reverse Words in a String 反转字符串
- [leetcode, python] Reverse Words in a String 反转字符串
- [leetcode, python] Reverse Words in a String 反转字符串
- 【LeetCode with Python】 Reverse Words in a String
- [leetcode]Reverse Words in a String(using Python)
- [leetcode, python] Reverse Words in a String 反转字符串
- [leetcode, python] Reverse Words in a String 反转字符串
- [leetcode, python] Reverse Words in a String 反转字符串
- Leetcode - Python - Reverse Words in a String
- leetcode 【 Reverse Words in a String 】python 实现
- leetcode:Reverse Words in a String【Python版】
- [leetcode, python] Reverse Words in a String 反转字符串
- LeetCode OJ 系列之151 Reverse Words in a String --Python
- using tail recursion to reverse words of line ( just for fun)
- Code Jam - Minimum Scalar Product for Python
- 151. Reverse Words in a String Leetcode Python
- [leetcode, python] Reverse Words in a String 反转字符串
- [leetcode, python] Reverse Words in a String 反转字符串