循环问题与局部变量

时间:2013-09-20 06:43:05

标签: python loops python-3.x while-loop

我正在使用Python(3.x)为作业创建一个简单的程序。它需要一个多行输入,如果有多个连续的空格,它会将它们删除并用一个空格替换它。 [这是最简单的部分。]它还必须打印整个输入中最连续的空格的值。

示例:

input = ("This is   the input.")

应打印:

This is the input.
3

我的代码如下:

def blanks():
    #this function works wonderfully!
    all_line_max= []
    while True:
        try:
            strline= input()
            if len(strline)>0:
                z= (maxspaces(strline))
                all_line_max.append(z)
                y= ' '.join(strline.split())
                print(y)
                print(z)
            if strline =='END':
                break
        except:
            break
        print(all_line_max)

def maxspaces(x):
    y= list(x)
    count = 0
    #this is the number of consecutive spaces we've found so far
    counts=[]
    for character in y:
        count_max= 0
        if character == ' ':
            count= count + 1
            if count > count_max:
                count_max = count
            counts.append(count_max)
        else:
            count = 0
    return(max(counts))


blanks()

据我所知,这可能非常低效,但似乎几乎可行。我的问题是:我想,一旦循环完成追加到all_lines_max,打印该列表的最大值。但是,如果没有在每一行上执行,那么似乎没有办法打印该列表的最大值,如果这有意义的话。关于我复杂代码的任何想法?

1 个答案:

答案 0 :(得分:1)

只需打印max的{​​{1}},就在您当前打印整个列表的位置:

all_line_max

但请将其留在 top 级别(所以dedent一次):

print(max(all_line_max))

并删除def blanks(): all_line_max = [] while True: try: strline = input() if strline: z = maxspaces(strline) all_line_max.append(z) y = ' '.join(strline.split()) print(y) if strline == 'END': break except Exception: break print(max(all_line_max)) 调用,该调用会打印每行的最大空格数。

每次找到空格时,您的print(z)功能会向maxspaces()列表添加count_max ;不是最有效的方法。你甚至不需要在那里保留一份清单; counts需要移动 out 循环,然后才能正确反映最大空间数。您也不必将句子转换为列表,您可以直接循环遍历字符串:

count_max
相关问题