首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >大写通过控制台输入和打印/返回输入的一系列行

大写通过控制台输入和打印/返回输入的一系列行
EN

Code Review用户
提问于 2019-02-27 13:15:49
回答 1查看 3.8K关注 0票数 3

我正在浏览github:https://github.com/zhiwehu/Python-programming-exercises/blob/master/100%2B%20Python%20challenging%20programming%20exercises.txt上流行的python实践练习。

我最近发现了递归函数。因此,当在上面的链接中询问以下内容时:

代码语言:javascript
复制
Question 9
Level 2

Question£º
Write a program that accepts sequence of lines as input and prints the lines after making all characters in the sentence capitalized.
Suppose the following input is supplied to the program:
Hello world
Practice makes perfect
Then, the output should be:
HELLO WORLD
PRACTICE MAKES PERFECT

我的答案是:

代码语言:javascript
复制
def capitalize_line(string=""):
    """Capitalize and add a newline to the input str(if present)"""
    inp = input("enter: ").upper()
    string = "\n".join([string, inp]) if string and inp else "".join([string, inp])
    if not inp:
        print(string)
        return string
    return capitalize_line(string=string)

例如,“HELLO”和“world”的两个输入将返回“HELLO\n world”。

这是一个合适的解决方案吗?毕多尼?

链接的答案是:

代码语言:javascript
复制
Solution:
lines = []
while True:
    s = raw_input()
    if s:
        lines.append(s.upper())
    else:
        break;

for sentence in lines:
    print sentence
EN

回答 1

Code Review用户

发布于 2019-02-28 09:45:18

尽管答案 by @Beno tPilatte很好,只要您希望将其保持为递归解决方案,下面是只使用生成器的解决方案。

首先,Python2将在不到一年的时间内不再受支持。。如果您还没有切换到Python 3,那么现在是时候了。作为一个小小的激励,我将在这个答案的其余部分假设Python 3。

现在,让我们从构建一个接受用户输入的生成器开始,直到输入一个空行:

代码语言:javascript
复制
def user_input():
    while True:
        s = input()
        if not s:
            return
        yield s

这很简单,现在我们已经完成了,因为我们可以直接使用str.upper,因为input的输出是一个字符串,所以不需要递归函数来完成:

代码语言:javascript
复制
def solution():
    for line in user_input():
        print(line.upper())

或者,我们可以链接生成器并使用map

代码语言:javascript
复制
def solution():
    for line in map(str.upper, user_input()):
        print(line)

正如您所看到的,无论Python中的堆栈大小有多大限制,它都要短得多,而且可读性更强。

票数 2
EN
页面原文内容由Code Review提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://codereview.stackexchange.com/questions/214395

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档