我正在浏览github:https://github.com/zhiwehu/Python-programming-exercises/blob/master/100%2B%20Python%20challenging%20programming%20exercises.txt上流行的python实践练习。
我最近发现了递归函数。因此,当在上面的链接中询问以下内容时:
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我的答案是:
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”。
这是一个合适的解决方案吗?毕多尼?
链接的答案是:
Solution:
lines = []
while True:
s = raw_input()
if s:
lines.append(s.upper())
else:
break;
for sentence in lines:
print sentence发布于 2019-02-28 09:45:18
尽管答案 by @Beno tPilatte很好,只要您希望将其保持为递归解决方案,下面是只使用生成器的解决方案。
首先,Python2将在不到一年的时间内不再受支持。。如果您还没有切换到Python 3,那么现在是时候了。作为一个小小的激励,我将在这个答案的其余部分假设Python 3。
现在,让我们从构建一个接受用户输入的生成器开始,直到输入一个空行:
def user_input():
while True:
s = input()
if not s:
return
yield s这很简单,现在我们已经完成了,因为我们可以直接使用str.upper,因为input的输出是一个字符串,所以不需要递归函数来完成:
def solution():
for line in user_input():
print(line.upper())或者,我们可以链接生成器并使用map:
def solution():
for line in map(str.upper, user_input()):
print(line)正如您所看到的,无论Python中的堆栈大小有多大限制,它都要短得多,而且可读性更强。
https://codereview.stackexchange.com/questions/214395
复制相似问题